如何确保 Jest 在“unhandledRejection"上失败? [英] How to ensure Jest fails on "unhandledRejection"?
问题描述
我们的单元测试在持续交付管道的容器中运行.
Our unit tests run in containers in our continuous delivery pipelines.
有时,我们不处理单元测试中的拒绝,但是,我认为这是不正确的,在我看来,管道应该失败.
Sometimes, we don't handle rejections in our unit tests, however, I don't think it's correct and in my opinion the pipeline should fail.
如何确保当我执行 jest
并且在测试期间发生 unhandledRejection
事件时,jest 会错误退出?
How can I make sure that when I execute jest
and during the tests an unhandledRejection
event occurs, jest will exit with error?
我试图在设置脚本中挂钩事件侦听器:
I tried to hook event listeners in a setup script:
/* jest.config.js */
module.exports = {
setupFiles: ['<rootDir>/test/setup.ts'],
// ...
}
在那个设置脚本中,我可以检测到 unhandledRejection
事件,但不幸的是,我不能开玩笑
and in that setup script, I can detect unhandledRejection
events, but unfortunately, I can't make jest break
process.on('unhandledRejection', () => {
console.error('Now what?');
console.error('I want to make sure that jest exits with an error!');
});
推荐答案
您可以创建一个 jest 配置文件 jest.config.js
并将以下条目放入其中:
You can create a jest config file jest.config.js
and put the following entry into it:
module.exports = {
...
setupFiles: ['<rootDir>/test/setup.js'],
...
};
然后在您的 setup.js
文件中,您可以执行以下操作:
And then in your setup.js
file, you can do something like this:
process.on('unhandledRejection', (err) => {
fail(err);
});
并且 unhandledRejection
将无法通过测试,但需要注意两个警告:
And unhandledRejection
will fail a test, though there are two caveates to be aware of:
- 在没有测试运行时拒绝的承诺的未处理拒绝将结束该过程.这可能就是您想要和期待的.
- 在运行新测试(不是启动承诺的测试)时拒绝的承诺未处理的拒绝将使新测试失败,而不是原始测试失败.这令人困惑,并且会导致难以跟踪错误.
作为上面提到的评论者,如果你的测试写得很好,那么你永远不应该遇到这种情况,但你并不总是有那么多控制权.
As a commenter mentioned above, if your tests are well written, then you should never hit this scenario, but you don't always have that much control.
这篇关于如何确保 Jest 在“unhandledRejection"上失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!