ValentinH / jest-fail-on-console

Utility to make jest tests fail when console.error() or any other methods are used
MIT License
141 stars 20 forks source link

Want fail on unhandled promise rejections #20

Closed brianabaker closed 1 year ago

brianabaker commented 2 years ago

Hello!

Can I use this package to fail on unhandled promise rejection warnings?

I want this to cause a failure: (node:38060) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

I tried adding the following code to a file I use in setupFiles

process.on("unhandledRejection", () => {
  console.error(
    `Unhandled promise rejection while running test!`,
  );
});

And I see my new error message is getting logged to my terminal, but the tests aren't failing. I have confirmed this package works great on other console.errors I have in other tests.

Thanks!

ValentinH commented 2 years ago

I'm not 100% sure. I'm wondering if it could be due to process.on("unhandledRejection" being added in setupFiles while this library is initialized setupFilesAfterEnv. Did you try moving your code in the latter file?

brianabaker commented 2 years ago

It doesn't work, and also if I move process.on("unhandledRejection" to setupFilesAfterEnv nothing outputs to the console. Not sure the why about that yet.

ValentinH commented 2 years ago

Sorry for the late response.

I tried to get this working but, as far as I understand, the console.error in process.on is executed too late. Indeed, the required cleanup code from jest-fail-on-console has already been executed at this point.

However, one approach that you can do is:

process.on('unhandledRejection', (err) => {
  console.error(err);
  throw new Error(`Unhandled promise rejection while running test!`);
});

This will actually make the test run fails completely which is better than nothing. See https://stackoverflow.com/a/58634792/1713469

ValentinH commented 1 year ago

Closing as there was no answer for a while. Comment to re-open 😉

blordpluto commented 1 year ago

@brianabaker If you are writing TypeScript, you might find linting useful to address this issue:

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-floating-promises.md