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

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...