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

108 views Asked by At

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!

1

There are 1 answers

6
Drew Reese On BEST ANSWER

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');
});

...