如何配置jest测试以使警告失败?
console.warn('stuff');
// fail test
Run Code Online (Sandbox Code Playgroud)
您可以使用以下简单覆盖:
let error = console.error
console.error = function (message) {
error.apply(console, arguments) // keep default behaviour
throw (message instanceof Error ? message : new Error(message))
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Jest setupFiles使它在所有测试中都可用。
在package.json
:
"jest": {
"setupFiles": [
"./tests/jest.overrides.js"
]
}
Run Code Online (Sandbox Code Playgroud)
然后将代码段放入 jest.overrides.js
对于那些使用create-react-app,不想运行的人npm run eject
,可以将以下代码添加到./src/setupTests.js
:
global.console.warn = (message) => {
throw message
}
global.console.error = (message) => {
throw message
}
Run Code Online (Sandbox Code Playgroud)
现在,当消息传递到console.warn
or时,jest 将失败console.error
。
有一个有用的 npm 包可以帮助您实现这一目标:jest-fail-on-console
它很容易配置。
npm i -D jest-fail-on-console
Run Code Online (Sandbox Code Playgroud)
在 Jest 的setupFilesAfterEnv选项中使用的文件中,添加以下代码:
import failOnConsole from 'jest-fail-on-console'
failOnConsole()
// or with options:
failOnConsole({ shouldFailOnWarn: false })
Run Code Online (Sandbox Code Playgroud)
jest.spyOn
我最近使用引入来v19.0.0
模拟warn
方法console
(通过上下文/对象访问)来实现这一点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();
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2602 次 |
最近记录: |