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

2019-03-26 04:32发布

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?

1条回答
Explosion°爆炸
2楼-- · 2019-03-26 05:00

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

查看更多
登录 后发表回答