How to use Jest with jsdom to test console.log?

Suppose you want test a function like this by printing a message:

function sayHello () { console.log('Hello!') }

You can use jest.spyOn function to change how console.log function behaves.

function sayHello () { console.log('Hello!') };
describe('logging "Hello"', () => {
  const log = jest.spyOn(global.console, 'log');
  sayHello();
  it('should print to console', () => {
    expect(log).toHaveBeenCalledWith('Hello!');
  });
});

OR you can redefine console object and add a key with jest.fn value, like this:

describe('sayHello prints "Hello!"', () => {
  const log = jest.fn()
  global.console = { log }
  sayHello()
  expect(log).toHaveBeenCalledWith('Hello!')
}

You can set console.log to by a spy like this:

global.console = {
  warn: jest.fn(),
  log: jest.fn()
}

// run your code

expect(global.console.log).toHaveBeenCalledWith('test')

As your test file runs in a separate thread you don't need to reset console to the original methods