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 opinio
Solution 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:
- Unhandled rejections from promises that reject when there is no test running will end the process. This is probably what you want and expect.
- 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.
Solution 2:
Adding the following flags when running jest did the trick for me:
--detectOpenHandles--forceExit--runInBand
Solution 3:
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
Post a Comment for "How To Ensure Jest Fails On "unhandledrejection"?"