The Qodesmith
The Qodesmith

Reputation: 3375

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

I'm just getting set up with Jest and I've successfully written unit tests that test the DOM. I have a library that types things on the screen, so I'm able to test just fine. In some cases, instead of throwing an error, my library will spit out a console.warn or console.log. Is it possible to use Jest to test that these console messages are happening?

Upvotes: 15

Views: 10397

Answers (2)

Purkhalo Alex
Purkhalo Alex

Reputation: 3627

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!')
}

Upvotes: 4

Andreas Köberle
Andreas Köberle

Reputation: 110892

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

Upvotes: 35

Related Questions