Unhandled promise rejection thrown in afterAll for Karma only after node upgrade

Viewed 121

How to solve unhandled promise rejection error in karma unit test?

Chrome Headless 102.0.5005.115 (Linux x86_64) ERROR
  An error was thrown in afterAll
  Unhandled promise rejection: [object Object] thrown
  Unhandled promise rejection: [object Object] thrown
Chrome Headless 102.0.5005.115 (Linux x86_64): Executed 1 of 23 ERROR (0.03 secs / 0.016 secs) 

this is the error I am getting when karma unit test is run on docker. There are no error when I tran same test on local karma.

local node v16.14.2

docker node v16.15.0

This error started coming when I upgraded docker node from v10.20.1 to v16.15.0

I am most certain that issue is in project js file itself but how to find the error cause. Please help! docker npm list:

npm list --depth=0
development_environment@1.0.0 /usr/src/app
+-- @babel/core@7.18.6
+-- @babel/preset-env@7.18.6
+-- eslint-config-plato@1.0.6
+-- eslint@8.19.0
+-- express@4.18.1
+-- fs-extra@10.1.0
+-- gulp-babel@8.0.0
+-- gulp-clean-css@4.3.0
+-- gulp-eslint@6.0.0
+-- gulp-header@2.0.9
+-- gulp-htmlhint@4.0.2
+-- gulp-replace@1.1.3
+-- gulp-sass@5.1.0
+-- gulp@4.0.2
+-- http-proxy-middleware@2.0.6
+-- jquery-mockjax@2.6.0
+-- karma-chrome-launcher@3.1.1
+-- karma-coverage@2.2.0
+-- karma-es6-shim@1.0.0
+-- karma-firefox-launcher@2.1.2
+-- karma-jasmine-jquery-2@0.1.1
+-- karma-jasmine@5.1.0
+-- karma-junit-reporter@2.0.1
+-- karma-requirejs@1.1.0
+-- karma-sonarqube-unit-reporter@0.0.23
+-- karma@6.4.0
+-- requirejs@2.3.6
+-- sass@1.53.0
`-- through2@4.0.2

Please guide if the question needs improvement. Thank you!

1 Answers

You're possibly running into this issue on jasmine a dependency of karma. They had changed their error detection logic so that it started reporting unhandled rejections that previously weren't.

So it applies a simple rule: whenever control is returned to the runtime, an unhandled rejection event is fired for every promise that has been rejected and not awaited (or .then-d)

Even though you have a recent Node version, you maybe have a version of the dependency from before this behavior was introduced.

If I understood correctly, you should be able to fix it in your tests by ensuring all rejected promises are handled before the test returns.

One suggested fix:

You could try explicitly handling the rejection immediately after creating the promise:

    const rejectingPromise = Promise.reject(new Error("Operation failed."));
    rejectingPromise.catch(() => {});
    await new Promise<void>((resolve) => setTimeout(resolve, 100));
    // [...]

The exact fix will depend on how the test that causes this looks like, but I guess you'll always be able to do something similar.

Update

This kind of fix didn't seem to work for the code of the original question, but might in other cases.

Related