How to ensure Jest fails on “unhandledRejection”?

岁酱吖の 提交于 2020-12-08 06:46:33

问题


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.

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'],
    // ...
}

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!');
});

回答1:


You can create a jest config file jest.config.js and put the following entry into it:

module.exports = {
  ...
  setupFiles: ['<rootDir>/test/setup.js'],
  ...
};

And then in your setup.js file, you can do something like this:

process.on('unhandledRejection', (err) => {
  fail(err);
});

And unhandledRejection will fail a test, though there are two caveates to be aware of:

  1. Unhandled rejections from promises that reject when there is no test running will end the process. This is probably what you want and expect.
  2. Unhandled rejections from promises that reject when a new test is running (not the one that initiated the promise) will fail the new test, not the original test. This is confusing and can make for difficult to track bugs.

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.




回答2:


In addition to @andrew-eisenberg answer, you can also config setup file in package.json as follows:

"jest": {
  ...
  "setupFiles": ["<rootDir>/../test/setup.ts"],
  ...
}

src doc




回答3:


Adding the following flags when running jest did the trick for me:

--detectOpenHandles --forceExit --runInBand 


来源:https://stackoverflow.com/questions/51105622/how-to-ensure-jest-fails-on-unhandledrejection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!