reactjsunit-testingreact-testing-libraryhttp-status-code-500mockserver

How to suppress red 500 error logs from a successful React Testing Library test in the console?


I have the following successful test, which expects a 500 error:

  it('shows the error state', async () => {
    server.use(
      rest.get(get(), async (req, res, ctx) => {
        return res(ctx.status(500), ctx.json(buildEeRestErrorResponse('user', '500')));
      })
    );

    renderForTests(<Page />);
    const welcomeHeading = await screen.findByRole('heading', { level: 1 });

    // This test passes
    expect(welcomeHeading.textContent).toEqual('Welcome');
  });

The problem is that I see this red error log in the console when I run all of my tests: enter image description here

Does anyone know how to suppress this scary looking error log? Thanks!


Solution

  • Suppressing error logs during a unit test may be a simple as adding jest-mock-console to your project's dev dependencies.

    npm install --save-dev jest-mock-console
    

    Example Usage:

    import mockConsole from 'jest-mock-console';
    
    let restoreConsole;
    beforeEach(() => {
      restoreConsole = mockConsole();
    });
    
    afterEach(() => {
      restoreConsole();
    });
    
    ...
    
    it('shows the error state', async () => {
      server.use(
        rest.get(get(), async (req, res, ctx) => {
          return res(ctx.status(500), ctx.json(buildEeRestErrorResponse('user', '500')));
        })
      );
    
      renderForTests(<Page />);
      const welcomeHeading = await screen.findByRole('heading', { level: 1 });
    
      // This test passes
      expect(welcomeHeading.textContent).toEqual('Welcome');
    });
    
    ...