1

I was trying to make a login page. In the server-side code, I added an express validator which will detect whether the email id is valid or not. In case it is not valid it will send an error message and upon receiving the error message an alert will appear containing the message email id is not valid.

I am using mock service worker for mocking the asynchronous response.

test code:

test("Alert appears on invalid email error", async () => {
    server.resetHandlers(
        rest.post("http://localhost:8080/login", (req, res, ctx) => {
            return res(
                ctx.json({
                    response: {
                        data: {
                            message: "Email id is not valid",
                        },
                    },
                })
            );
        })
    );

    const user = userEvent.setup();
    render(<App />);

    const emailTextEl = screen.getByLabelText(/email address/i);
    const passwordTextEl = screen.getByLabelText(/password/i);
    const buttonEl = screen.getByRole("button", { name: "Login" });

    await user.type(emailTextEl, "abc");
    await user.type(passwordTextEl, "123");
    await user.click(buttonEl);

    const alertEl = await screen.findByRole("alert");

    expect(alertEl).toBeInTheDocument();
});

Upon running npm run test in the command prompt I get a axios error console like:

 console.log
    AxiosError {
      message: 'Network Error',
      name: 'AxiosError',
      code: 'ERR_NETWORK',
      config: {
        transitional: {
          silentJSONParsing: true,
          forcedJSONParsing: true,
          clarifyTimeoutError: false
        },
        adapter: [ 'xhr', 'http' ],
        transformRequest: [ [Function: transformRequest] ],
        transformResponse: [ [Function: transformResponse] ],
        timeout: 0,
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        maxBodyLength: -1,
        env: { FormData: [class FormData], Blob: [class Blob] },
        validateStatus: [Function: validateStatus],
        headers: AxiosHeaders {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json'
        },
        cancelToken: CancelToken { promise: [Promise], _listeners: [Array] },
        method: 'post',
        url: '/login',
        data: '{"emailId":"hello","password":"12345"}'
      },
      request: XMLHttpRequestOverride {
        _events: [],
        log: [Function: debug] {
          namespace: 'xhr:request POST /login',
          useColors: false,
          color: 161,
          extend: [Function: extend],
          destroy: [Function: deprecated],
          enabled: [Getter/Setter],
          inspectOpts: {},
          log: undefined
        },
        UNSENT: 0,
        OPENED: 1,
        HEADERS_RECEIVED: 2,
        LOADING: 3,
        DONE: 4,
        onreadystatechange: null,
        onabort: [Function: handleAbort],
        onerror: [Function: handleError],
        onload: null,
        onloadend: [Function: onloadend],
        onloadstart: null,
        onprogress: null,
        ontimeout: [Function: handleTimeout],
        url: '/login',
        method: 'POST',
        readyState: 1,
        withCredentials: false,
        status: 200,
        statusText: 'OK',
        response: null,
        responseType: 'text',
        responseText: null,
        responseXML: null,
        responseURL: '',
        upload: {},
        timeout: 0,
        _requestHeaders: HeadersPolyfill {
          [Symbol(normalizedHeaders)]: [Object],
          [Symbol(rawHeaderNames)]: [Map]
        },
        _responseHeaders: HeadersPolyfill {
          [Symbol(normalizedHeaders)]: {},
          [Symbol(rawHeaderNames)]: Map(0) {}
        },
        async: true,
        user: undefined,
        password: undefined
      }
    }

I could see the request but no response data in the console data.

To reproduce the same in your system one can clone the repo from :https://github.com/pawan-kr1997/learn-test

In the email id field enter "ABC" and in the password field enter "123".

On running the above test I am getting an error that alertEl is not being detected. But since this element is being shown asynchronously then findByRole is appropriate according to me.

I don't know if I am using the msw response the right way. Please guide me.

Pawan
  • 459
  • 5
  • 17
  • If clicking the button updates react state you need to wrap that inside of an `act()`. `await act( async () => {await user.click(buttonEl);})`. – morganney Jan 22 '23 at 14:54
  • @morganney, I tried your solution but the error persists – Pawan Jan 26 '23 at 07:50

0 Answers0