author: Krasimir Tsonev

Hi there, I'm . Senior front-end engineer with over 13 years of experience. I write, speak and occasionally code stuff. Follow me on Twitter, GitHub, Facebook or LinkedIn

Mocking console methods with Jest

I'm recently working on two OS libraries. Both I'm unit testing with Jest. There is some logic that leads to a warning which I'm doing with console.warn. In the unit tests this is happening quite often so I want to suppress it. Also I want to verify that it happens on the right place.

So, check out the following code:

const warn = jest.spyOn(console, "warn").mockImplementation(() => {});

Notice the mockImplementation. This basically says "instead of the original console.warn please run this function". In this case we are placing an empty function so we don't see the messages in the terminal. If we miss the mockImplementation we'll still have the mock but the actual warning will appear.

The warn object that we have as a result of spyOn is a mock. The same as the one returned by jest.fn(). Which means that we can use something like this:


And of course we shouldn't forget to reset the spy at the end of the test with:

If you enjoy this post, share it on Twitter, Facebook or LinkedIn. Or maybe comment below: