如何将Jest与jsdom一起使用来测试console.log? [英] How to use Jest with jsdom to test console.log?
问题描述
我刚刚开始使用Jest进行设置,并且我已经成功编写了测试DOM的单元测试.我有一个库,它可以在屏幕上输入内容,因此我可以进行测试.在某些情况下,我的库不会抛出错误,而是吐出console.warn
或console.log
.是否可以使用Jest测试这些控制台消息是否正在发生?
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?
推荐答案
您可以通过这样的间谍将console.log设置为:
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')
由于测试文件在单独的线程中运行,因此无需将console
重置为原始方法
As your test file runs in a separate thread you don't need to reset console
to the original methods
这篇关于如何将Jest与jsdom一起使用来测试console.log?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!