Skip to main content

MockServerWorker is not handling responses when using fecth in react

I'm doing test driven development in react course -

I'm trying to development test for post request. Below is by react code.

import React from "react";
import axios from "axios";

class SignUpPage extends React.Component {

    state = {
    }

    onChange = (event) => {
        const {id, value} = event.target;
        this.setState({
            [id]:value
        })
    };

    onChangeUsername = (event) => {
        const currentValue = event.target.value;
        this.setState({
            username: currentValue,
          //  disabled: currentValue !== this.state.confirmPassword
        });
    };

    onChangeEmail = (event) => {
        const currentValue = event.target.value;
        this.setState({
            email: currentValue,
          //  disabled: currentValue !== this.state.confirmPassword
        });
    };
    
    onChangePassword= (event) => {
        const currentValue = event.target.value;
        this.setState({
            password: currentValue,
          //  disabled: currentValue !== this.state.confirmPassword
        });
    };

    onChangeConfirmPassword= (event) => {
        const currentValue = event.target.value;
        this.setState({
            confirmPassword: currentValue,
         //   disabled: currentValue !== this.state.password
        });
    };

    submit = (event) => {
        event.preventDefault();
      const {username, email, password } =  this.state;
      const body = {
          username, email, password
      }
      //axios.post('/api/1.0/users', body);
      fetch("/api/1.0/users", {
          method: 'POST',
          headers : {
              "Content-Type": "application/json"
          },
          body: JSON.stringify(body)
      });
    };

    render() {
        let disabled = true;
        const { password, confirmPassword} = this.state;
        if(password && confirmPassword) {
            disabled = password !== confirmPassword;
        }

        // setTimeout(() => {
        //     this.setState({disabled: false});
        //     console.log('updating disabled');
        // }, 1000);

        return (
        <div className="col-lg-6 offset-lg-3 col-md-8 offset-md-2">
            <form className="card mt-5">
            <h1 className="text-center card-header">Sign Up</h1>

            <div className="card-body">
            <div className="mb-3">            
            <label htmlFor="username" className="form-label">Username</label>
            <input id="username"onChange={this.onChange} className="form-control"/>
            </div>

            <div className="mb-3"><label htmlFor="email" className="form-label">E-mail</label>
            <input id="email" onChange={this.onChange} className="form-control mb-4"/>
            </div>
            <div className="mb-3"><label htmlFor="password" className="form-label">Password</label>
            <input id="password" type="password" onChange={this.onChange} className="form-control"/>
            </div>
            <div className="mb-3"><label htmlFor="confirmPassword" className="form-label">Confirm Password</label>
            <input id="confirmPassword" type="password" onChange={this.onChange} className="form-control"/>
            </div>
            <div className="text-right">
            <button disabled={disabled} onClick={this.submit} className="btn btn-primary">Sign Up</button>
            </div>
            </div>
            </form>
        </div>
        );
    }
}


export default SignUpPage;

and the test for the post request when the button is clicked is -

import SignUpPage from "./SignUpPage";
import {render, screen} from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const axios = require('axios').default; 
import { setupServer} from "msw/node";
import { rest } from "msw";

describe("Interactions", () => {
    

    it("sends username, email and password to backend after clicking the button", async () => {
        let reqBody;
        const server = setupServer(
            rest.post("/api/1.0/users", (req, res, ctx) => {
                console.log("the message is");
                reqBody = req.body;
                return res(ctx.status(200));
            })
        );

        server.listen();
        render(<SignUpPage/>);
        const usernameInput = screen.getByLabelText('Username');
        const emailInput = screen.getByLabelText('E-mail');
        const passwordInput = screen.getByLabelText('Password');
        const confirmPassword = screen.getByLabelText('Confirm Password');

        userEvent.type(usernameInput, 'user1');
        userEvent.type(emailInput, 'user1@mail.com');
        userEvent.type(passwordInput, 'P4ssw0rd');
        userEvent.type(confirmPassword, 'P4ssw0rd');
        const button = screen.queryByRole('button', {name: 'Sign Up'});
        expect(button).toBeEnabled();
        userEvent.click(button);


        await new Promise(resolve => setTimeout(resolve, 1500));

       // const firstCallofMockFunction = mockFn.mock.calls[0];
        //const body = JSON.parse(firstCallofMockFunction[1].body);


        expect(reqBody).toEqual({
            username: 'user1',
            email: 'user1@mail.com',
            password: 'P4ssw0rd'
        });

    });

    
});

When the test is run I get below error -

console.warn [MSW] Warning: captured a request without a matching request handler:

• POST http://localhost:3000/api/1.0/users

If you still wish to intercept this unhandled request, please create a request handler for it. Read more: https://mswjs.io/docs/getting-started/mocks

console.error Error: Error: connect ECONNREFUSED ::1:3000 at Object.dispatchError (/home/rajkumar/Coding/react/react-tdd/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:63:19) at Request. (/home/rajkumar/Coding/react/react-tdd/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:655:18) at Request.emit (node:events:539:35) at NodeClientRequest. (/home/rajkumar/Coding/react/react-tdd/node_modules/jsdom/lib/jsdom/living/helpers/http-request.js:121:14) at NodeClientRequest.emit (node:events:539:35) at NodeClientRequest.Object..NodeClientRequest.emit (/home/rajkumar/Coding/react/react-tdd/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.ts:284:22) at Socket.socketErrorListener (node:_http_client:454:9) at Socket.emit (node:events:527:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) undefined

    ● Interactions › sends username, email and password to backend after clicking the button

    expect(received).toEqual(expected) // deep equality

    Expected: {"email": "user1@mail.com", "password": "P4ssw0rd", "username": "user1"}
    Received: undefined

      94 |         await new Promise(resolve => setTimeout(resolve, 1500));
      95 |
    > 96 |         expect(reqBody).toEqual({
         |                         ^
      97 |             username: 'user1',
      98 |             email: 'user1@mail.com',
      99 |             password: 'P4ssw0rd'

      at Object.<anonymous> (src/pages/SignUpPage.spec.js:96:25)

The complete code is on github here. When I use axios.post instead of fetch it is working fine. How can I fix this error -

Via Active questions tagged javascript - Stack Overflow https://ift.tt/7nBiP2V

Comments

Popular posts from this blog

Confusion between commands.Bot and discord.Client | Which one should I use?

Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents) . Now I know slightly about the difference but I get errors from different places from my code when I use either of them and its confusing. Especially since there has a few changes over the years in discord.py it is hard to find the real difference. I tried sticking to discord.Client then I found that there are more features in commands.Bot . Then I found errors when using commands.Bot . An example of this is: When I try to use commands.Bot client = commands.Bot(command_prefix=">",intents=intents) async def load(): for filename in os.listdir("./Cogs"): if filename.endswith(".py"): client.load_extension(f"Cogs.{filename[:-3]}") The above doesnt giveany response from my Cogs ...

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Where and how is this Laravel kernel constructor called? [closed]

Where and how is this Laravel kernel constructor called? public fucntion __construct(Application $app, $Router $roouter) { } I have read the documentation and some online tutorial but I can find any clear explanation. I am learning Laravel and I am wondering where does this kernel constructor receives its arguments from. "POSTMOTERM" CLARIFICATION: Here is more clarity.I have checked the boostrap/app.php and it is only used for boostrapping the interfaces into the container class. What is not clear to me is where and how the Kernel class is instatiated and the arguments passed to the object calling the constructor.Something similar to; obj = new kernel(arg1,arg2) or, is the framework using some magic functions somewhere? Special gratitude to those who burn their eyeballs and brain cells on this trivia before it goes into a full blown menopause alias "MARKED AS DUPLICATE". To some of the itchy-finger keyboard warriors, a.k.a The mods,because I believe in th...