Suppose you want to test such a function by typing a message:
function sayHello () { console.log('Hello!') }
You can use the jest.spyOn function to change the behavior of the console.log function.
describe('sayHello prints "Hello!"', () => { const log = jest.spyOn(global.console, 'log') sayHello() expect(log).toHaveBeenCalledWith('Hello!') })
OR you can override the console object and add a key with the value jest.fn , for example:
describe('sayHello prints "Hello!"', () => { const log = jest.fn() global.console = { log } sayHello() expect(log).toHaveBeenCalledWith('Hello!') }
source share