2021-02-28

How do I suppress expected Axios error messages when testing error states with react-testing-library?

I'm working on adapting some React code of mine to use @testing-library/react, react-query, and msw to mock network calls that I make using axios.

So far (after some brainbending) I've got it working with this code! (yay!)

The test in question (simplified):

import React from 'react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { screen, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
import { queryCache } from 'react-query';
import userEvent from '@testing-library/user-event';
import Login from '../Login';
import { render, queryClient } from '~/testhelpers/helpers.integration';
// #endregion imports

const server = setupServer(
    // ...default setup for successful request; not relevant here
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

describe('rendering', () => {
    describe('error', () => {
        it.only('should render error message when request fails', async () => {
            server.use(
                rest.post(`${API_BASE_URL}api/auth/token`, (req, res, ctx) => {
                    return res(ctx.status(400), ctx.json('Invalid username or password.'));
                })
            );
            render(<Login />);
            const usernameInput = screen.getByLabelText('Username');
            const passwordInput = screen.getByLabelText('Password');
            const submitInput = screen.getByRole('button', { name: 'Login' });
            userEvent.type(usernameInput, 'testUsername');
            userEvent.type(passwordInput, 'testPassword');
            userEvent.click(submitInput);
            await waitFor(() => {
                expect(screen.getByText('Invalid username or password.')).toBeInTheDocument();
            });
        });
    });
});

Again, this test works! Hooray! But the issue is that I am making axios think (via msw) that it is receiving a 400 response for this query, and I get this big chunk of error message in my console when I run this test with Jest:

 PASS  src/display/views/login/__tests__/Login.spec.js
  rendering
    error
      √ should hide loading indicator and render error message when request fails (522 ms)

  console.error
    Error: Request failed with status code 400
        at createError (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\axios\lib\core\createError.js:16:15)
        at settle (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\axios\lib\core\settle.js:18:12)
        at XMLHttpRequestOverride.handleLoad [as onreadystatechange] (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\axios\lib\adapters\xhr.js:59:7)
        at XMLHttpRequestOverride.triggerReadyStateChange (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\node-request-interceptor\src\interceptors\XMLHttpRequest\XMLHttpRequestOverride.ts:133:33)     
        at XMLHttpRequestOverride.trigger (C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\node-request-interceptor\src\interceptors\XMLHttpRequest\XMLHttpRequestOverride.ts:145:12)
        at C:\Users\me\Documents\_Programming\GitHub\my-project\node_modules\node-request-interceptor\src\interceptors\XMLHttpRequest\XMLHttpRequestOverride.ts:306:18
        at runNextTicks (internal/process/task_queues.js:62:5)
        at processTimers (internal/timers.js:489:9) {
      config: {
        adapter: [Function: xhrAdapter],
        transformRequest: { '0': [Function: transformRequest] },
        transformResponse: { '0': [Function: transformResponse] },
        timeout: 0,
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        headers: {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json;charset=utf-8'
        },
        method: 'post',
        url: 'http://baseurl/api/auth/token',
        data: '{"username":"testUsername","password":"testPassword"}'
      },
      request: XMLHttpRequestOverride {
        requestHeaders: {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json;charset=utf-8'
        },
        responseHeaders: { 'x-powered-by': 'msw', 'content-type': 'application/json' },
        _events: [],
        UNSENT: 0,
        OPENED: 1,
        HEADERS_RECEIVED: 2,
        LOADING: 3,
        DONE: 4,
        onreadystatechange: [Function: handleLoad],
        onabort: null,
        onerror: [Function: handleError],
        onload: null,
        onloadend: null,
        onloadstart: null,
        onprogress: null,
        ontimeout: [Function: handleTimeout],
        url: 'http://baseurl/api/auth/token',
        method: 'POST',
        readyState: 4,
        withCredentials: false,
        status: 400,
        statusText: 'Bad Request',
        data: '{"username":"testUsername","password":"testPassword"}',
        response: '"Invalid username or password."',
        responseType: 'text',
        responseText: '"Invalid username or password."',
        responseXML: null,
        responseURL: '',
        upload: null,
        timeout: 0,
        async: true,
        user: undefined,
        password: undefined
      },
      response: {
        data: 'Invalid username or password.',
        status: 400,
        statusText: 'Bad Request',
        headers: { 'x-powered-by': 'msw', 'content-type': 'application/json' },
        config: {
          adapter: [Function: xhrAdapter],
          transformRequest: [Object],
          transformResponse: [Object],
          timeout: 0,
          xsrfCookieName: 'XSRF-TOKEN',
          xsrfHeaderName: 'X-XSRF-TOKEN',
          maxContentLength: -1,
          validateStatus: [Function: validateStatus],
          headers: [Object],
          method: 'post',
          url: 'http://baseurl/api/auth/token',
          data: '{"username":"testUsername","password":"testPassword"}'
        },
        request: XMLHttpRequestOverride {
          requestHeaders: [Object],
          responseHeaders: [Object],
          _events: [],
          UNSENT: 0,
          OPENED: 1,
          HEADERS_RECEIVED: 2,
          LOADING: 3,
          DONE: 4,
          onreadystatechange: [Function: handleLoad],
          onabort: null,
          onerror: [Function: handleError],
          onload: null,
          onloadend: null,
          onloadstart: null,
          onprogress: null,
          ontimeout: [Function: handleTimeout],
          url: 'http://baseurl/api/auth/token',
          method: 'POST',
          readyState: 4,
          withCredentials: false,
          status: 400,
          statusText: 'Bad Request',
          data: '{"username":"testUsername","password":"testPassword"}',
          response: '"Invalid username or password."',
          responseType: 'text',
          responseText: '"Invalid username or password."',
          responseXML: null,
          responseURL: '',
          upload: null,
          timeout: 0,
          async: true,
          user: undefined,
          password: undefined
        }
      }
    }

      at CustomConsole.console.error (node_modules/@testing-library/react/dist/act-compat.js:52:34)
      at node_modules/react-query/lib/core/mutation.js:115:32

I think, to a certain extent, this is expected, but it's REALLY unnecessary spam in my tests given that I am expecting and in fact wanting that request to fail. Is there a best practice way to remove this unnecessary log via config for Jest, RTL, msw, or Axios?



from Recent Questions - Stack Overflow https://ift.tt/2NKFXIQ
https://ift.tt/eA8V8J

No comments:

Post a Comment