DEV Community

Cover image for Hide RED console.error LOG WALL while testing errors with jest
Martin Emmert
Martin Emmert

Posted on

Hide RED console.error LOG WALL while testing errors with jest

While provoking errors on purpose during tests the red error logs can get really annoying and hide potential crucial information from your eyes.

Following a discussion on this issue leads to a nice solution by Kent C. Dodds.

Comment for #5267

I decided to not use omitJSDOMErrors for two reasons:

  1. The giant log I was seeing which resulted in #5227 also appears in the browser so it makes sense we see it in the JSDOM environment as well.
  2. @domenic said: "jsdomErrors are fired for many other cases as well, besides JavaScript errors. E.g. failed CSS parsing or image loading."

Because #5227, the console JSDOM uses is the same one you have in your tests, so it's mockable now. So if you don't like the errors that are logged, you can simply do:

beforeEach(() => {
  jest.spyOn(console, 'error')
  console.error.mockImplementation(() => {})
})

afterEach(() => {
  console.error.mockRestore()
})
Enter fullscreen mode Exit fullscreen mode

So I would recommend against making this change.


tl;dr; A snippet to hide console.error logs during testing error messages.

beforeEach(() => {
  jest.spyOn(console, 'error')
  // @ts-ignore jest.spyOn adds this functionallity
  console.error.mockImplementation(() => null);
});

afterEach(() => {
  // @ts-ignore jest.spyOn adds this functionallity
  console.error.mockRestore()
})
Enter fullscreen mode Exit fullscreen mode

Cover Photo by Markus Spiske on Unsplash

Top comments (1)

Collapse
 
jsjoeio profile image
Joe Previte (he/him) • Edited

Just used this today and still works. thank you!

By the way, to avoid using @ts-ignore you can do this:

  let spy: jest.SpyInstance;
  beforeEach(() => {
    spy = jest.spyOn(console, 'error').mockImplementation(() => null);
  });
  afterEach(() => {
    spy.mockRestore();
  });
Enter fullscreen mode Exit fullscreen mode