How do I test a jest console.log
If you want to check that console.log
received the right parameter (the one that you passed in) you should check mock
of your jest.fn()
.
You also have to invoke your log
function, otherwise console.log
is never invoked:
it('console.log the text "hello"', () => {
console.log = jest.fn();
log('hello');
// The first argument of the first call to the function was 'hello'
expect(console.log.mock.calls[0][0]).toBe('hello');
});
or
it('console.log the text "hello"', () => {
console.log = jest.fn();
log('hello');
// The first argument of the first call to the function was 'hello'
expect(console.log).toHaveBeenCalledWith('hello');
});
If you're going with this approach don't forget to restore the original value of console.log
.
Another option is to use jest.spyOn
(instead of replacing the console.log
it will create a proxy to it):
it('console.log the text "hello"', () => {
const logSpy = jest.spyOn(console, 'log');
console.log('hello');
expect(logSpy).toHaveBeenCalledWith('hello');
});
Read more here.
Or you could do it like this:
it('calls console.log with "hello"', () => {
const consoleSpy = jest.spyOn(console, 'log');
console.log('hello');
expect(consoleSpy).toHaveBeenCalledWith('hello');
});