本文介绍了如何确保Jest在"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事件,玩笑会退出并显示错误?

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.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:

  1. 未执行测试时拒绝的承诺中未处理的拒绝将结束该过程.这可能就是您想要和期望的.
  2. 未处理的来自承诺的拒绝会在新测试正在运行时拒绝(而不是发起承诺的那个)将使新测试(而不是原始测试)失败.这令人困惑,并且可能导致难以跟踪错误.

作为上面提到的评论者,如果您的测试写得很好,那么您永远都不会遇到这种情况,但是您并不总是拥有那么多的控制权.

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"上失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:52