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!');
});
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:
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.
Adding the following flags when running jest did the trick for me:
--detectOpenHandles --forceExit --runInBand
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With