My 5th book "50 Tips on JavaScript" is on sale. Go get it from https://50tips.dev.
Illustrated guide to 50 of the most interesting JavaScript topics.

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:

expect(warn).toBeCalledWith('...');

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

warn.mockReset();
If you enjoy this post, share it on Twitter, Facebook or LinkedIn. To leave a comment go here.