如何将jest测试配置为在出现警告时失败?
console.warn('stuff');
// fail test发布于 2018-05-29 20:38:54
您可以使用这个简单的覆盖:
let error = console.error
console.error = function (message) {
error.apply(console, arguments) // keep default behaviour
throw (message instanceof Error ? message : new Error(message))
}您可以使用Jest setupFiles使其在所有测试中都可用。
在package.json中:
"jest": {
"setupFiles": [
"./tests/jest.overrides.js"
]
}然后将代码片段放入jest.overrides.js
发布于 2017-10-11 10:05:20
我最近使用v19.0.0中引入的jest.spyOn实现了这一点,以模拟console的warn方法(它是通过global上下文/对象访问的)。
然后,可以expect表示模拟的warn没有被调用,如下所示。
describe('A function that does something', () => {
it('Should not trigger a warning', () => {
var warn = jest.spyOn(global.console, 'warn');
// Do something that may trigger warning via `console.warn`
doSomething();
// ... i.e.
console.warn('stuff');
// Check that warn was not called (fail on warning)
expect(warn).not.toHaveBeenCalled();
// Cleanup
warn.mockReset();
warn.mockRestore();
});
});发布于 2019-01-26 03:04:36
对于那些使用create-react-app而不想运行npm run eject的用户,可以在./src/setupTests.js中添加以下代码
global.console.warn = (message) => {
throw message
}
global.console.error = (message) => {
throw message
}现在,当消息传递到console.warn或console.error时,jest将失败。
https://stackoverflow.com/questions/28615293
复制相似问题