Search code examples
angularunit-testingjasminekarma-runnerfreeze

Karma hangs for 30 seconds after successfully executing unit tests


After the successful execution of all unit tests, Karma hangs for 30 seconds and then outputs the following message:

Chrome Headless 114.0.5735.35 (Windows 10) ERROR
  Disconnected , because no message in 30000 ms.
Chrome Headless 114.0.5735.35 (Windows 10): Executed 634 of 634 DISCONNECTED (34.58 secs / 3.303 secs)
Chrome Headless 114.0.5735.35 (Windows 10) ERROR
Chrome Headless 114.0.5735.35 (Windows 10): Executed 634 of 634 DISCONNECTED (34.58 secs / 3.303 secs)

I read a lot of posts here on SO but none of them handles exactly the issue which I'm seeing. After investigating deeper, it turned out that surprisingly the number of tests matters! When removing tests so that the number of tests goes down to exactly 621, everything works fine. When adding one more test (no matter which ... even an empty it("should...",()=>{}) ) it hangs.

I'm using the following plugins in karma.conf.js:

require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma')

all of them have the latest available versions.

This is the debug output. It looks the same in good case (just without the red error message at the bottom).

enter image description here

Observations

  • When removing the --code-coverage option from ng test in package.json, the number of tests can be increased until it reaches a point where it hangs again.
  • First it looked like the issue is hardly reproducible. It turned out that this was caused by a default setting of Karma which causes the tests to be executed in a random order. Adding random: false to the jasmine section of karma.conf.js made it 100% reproducible.

Solution

  • I found a bug in Karma and created this pull request:

    https://github.com/karma-runner/karma/pull/3852

    But unfortunately it turned out that Karma was deprecated in April 2023 (https://github.com/Leaflet/Leaflet/issues/8939)! Thus, most likely no PRs will be merged anymore. If somebody needs to fix the issue, just have a look into the PR. Its very simple (only two lines of code).

    The explanation for the error is, that obviously when handling a high number of tests, it can happen that after finishing all tests (and thus closing the connection to the browser), still some log messages can come in. Karma writes these to the log, but also mistakenly re-triggers the inactivity timeout. The running timer obviously prevents Node from shutting down the process and this causes the 30sec hang. My fix prevents the timer from being triggered if the Karma status is DISCONNECTED.