How to mock `console.error` or other `console` methods with Jest
Posted on
Today a quick one I tend to always hunt into older code I authored to remember
how to do it. So to serve my future self as well as benefit the community, here
is how one can mock console methods with the Jest testing framework.
Let's go over an hopefully straight-forward example that mocks the
console.error method:
describe('My super duper component', async () => {
let consoleErrorSpy;
beforeEach(() => {
errorSpy = jest.spyOn(global.console, 'error').mockImplementation(() => {});
// Hint: It could work without the `.mockImplementation...` part but
// your Jest run output would be cluttered with the errors printed out.
});
afterEach(() => {
errorSpy.mockRestore();
});
it('logs an error if the wrapper is `undefined`', () => {
mySuperDuperComponent(/* missing `wrapper` argument */);
expect(errorSpy).toHaveBeenCalledTimes(1); // i.e it has been called once
expect(errorSpy).toHaveBeenCalledWith('Could not init super duper component. Wrapper not found.');
});
// ...
});
For the other console methods, just swap error and Error with their
equivalent (e.g. warn and Warn, log and Log...).