Fix Karma Tests Hanging with Headless Chrome in Angular
In this article
Karma tests hanging with Headless Chrome in Angular usually means the browser process never finishes loading or the test runner times out waiting for a connection. This guide walks you through the most common causes and fixes, from configuration tweaks to environment checks. You'll need a working Angular project with Karma already set up (the default setup from Angular CLI is fine).
What You'll Need
- An Angular project with Karma and Jasmine (or similar) already configured
- Access to the project's
karma.conf.jsfile - Chrome or Chromium installed on your machine (for local debugging)
- Command line access to run
ng test
Step-by-Step
- Identify the exact symptom. Before changing anything, run
ng test --watch=false --browsers=ChromeHeadlessand note where it hangs: does it hang after "Starting ChromeHeadless"? Does it show "Executed 0 of 0"? Does it hang on a specific test file? This tells you whether it's a browser launch issue, a connection issue, or a test execution issue. - Update Karma and related packages. Outdated versions often cause hanging. Run
npm update karma karma-chrome-launcher karma-jasmine jasmine-core(or the equivalents for your test framework). Then deletenode_modulesandpackage-lock.json, runnpm installagain, and retry the tests. - Increase Karma's browser disconnect and capture timeouts. In
karma.conf.js, setbrowserDisconnectTimeout(default 2000ms) to something like 10000,browserNoActivityTimeout(default 10000) to 60000, andcaptureTimeout(default 60000) to 120000. These give the browser more time to start and respond. - Add flags to ChromeHeadless to prevent crashes or hangs. In the custom launcher configuration, add flags like
--no-sandbox(common in CI or Docker),--disable-gpu,--disable-dev-shm-usage(fixes shared memory issues in containers), and--disable-setuid-sandbox. Example:customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'] } }Then run with--browsers=ChromeHeadlessNoSandbox. - Check if the hang is caused by a specific test or module. Temporarily comment out test files or use
fdescribe/fitto isolate. If a particular test hangs, it might be due to an infinite loop, a pending promise, or a long-running timer. Fix the test itself. - Ensure all async operations are properly handled. In your tests, make sure you call
done()in async callbacks, or useasync/awaitwithwaitForAsyncorfakeAsynccorrectly. A missingdone()will cause the test to hang forever. - Check for memory leaks or heavy DOM operations. If tests are slow, they might hit the default
browserNoActivityTimeout. Increase it as in step 3, but also look for tests that create many DOM elements or large data structures. - Update your Angular and CLI versions. If you're on an older Angular version, consider upgrading to the latest LTS (or at least a recent one). Headless Chrome compatibility issues are often fixed in newer releases.
- Try a different headless browser. If ChromeHeadless continues to hang, try
ChromeHeadlessCI(if available) or use FirefoxHeadless viakarma-firefox-launcher. This can help isolate whether it's a Chrome-specific issue. - Run with a non-headless browser to see errors. Temporarily run
ng test --browsers=Chrome(non-headless). If tests pass, the issue is specific to headless mode. If they hang too, the problem is in your tests or configuration. - Check for zombie Chrome processes. Sometimes old Chrome processes linger and interfere. On Linux/macOS run
pkill -f ChromeHeadlessorkillall chrome(Windows:taskkill /F /IM chrome.exe), then rerun tests. - Review your
karma.conf.jsfor incorrectfilesorpreprocessors. Ensure that all test files are included and that preprocessors likekarma-coverageare not causing hangs. Try disabling coverage temporarily by removingcoverageIstanbulReporterand thecoveragepreprocessor.
Common Mistakes
- Ignoring the
--no-sandboxflag in CI or Docker environments. This is the number one cause of Chrome hanging in containers. - Using an outdated
karma-chrome-launcherthat doesn't support the installed Chrome version. - Forgetting to call
done()in async tests, especially when usingsetTimeoutorPromise. - Setting
singleRun: truebut not using--watch=falsewithng test, causing confusion about when tests finish. - Having a test that intentionally calls
window.close()orprocess.exit(), which can kill the browser.
Tips
- Use
--source-map=falseinng testto reduce memory usage and speed up execution. - If you're using Angular CLI, consider switching to
ng test --browsers=ChromeHeadlessCIwhich is a predefined launcher with safe flags for CI. - Keep your
karma.conf.jssimple. Remove unused plugins and reporters to reduce overhead. - Run tests with
--code-coverageonly when needed, as it can slow down and sometimes hang the process. - If you're on Windows, try running tests in an elevated command prompt if you suspect permission issues.
Troubleshooting
If the steps above don't resolve the hang, try these additional checks:
- Enable verbose logging: Run
ng test --browsers=ChromeHeadless --log-level=debugand look at the Karma output. It will show where the hang occurs (e.g., "Waiting for browser to connect"). - Check Chrome's own logs: Add the flag
--enable-loggingto the launcher flags and see if Chrome writes any error messages to the console. - Test with a minimal configuration: Create a temporary
karma.conf.jsthat only loads one simple spec file. If that works, gradually add your actual files until you find the culprit. - Check system resources: If your machine is low on memory or CPU, the browser might not start in time. Close other applications and try again.
- Reinstall dependencies: Sometimes a corrupted
node_modulescauses weird issues. Delete it and runnpm installagain. - Try a different Node.js version: If you're using Node 17+, there are known issues with some Karma versions. Consider using Node 16 LTS.
Frequently Asked Questions
Why does my Karma test hang only in CI, not locally?
CI environments often run in containers with limited resources and no sandboxing. Adding --no-sandbox and --disable-dev-shm-usage flags usually fixes it.
What does browserNoActivityTimeout do?
It's the maximum time Karma waits for the browser to do something (like executing a test) before considering it dead. If your tests are slow, increase this value.
Can I use a different headless browser instead of Chrome?
Yes, you can use FirefoxHeadless (via karma-firefox-launcher) or even EdgeHeadless (via karma-edge-launcher). This can help if Chrome is the problem.
My tests pass with --browsers=Chrome but hang with ChromeHeadless. Why?
Headless mode has different behavior with some features like animations, WebGL, or certain DOM APIs. Check if any tests rely on those. Also, headless mode might have default flags that conflict with your app.
How do I know if the hang is in the browser or in Karma?
Look at the Karma console output. If it says "Starting ChromeHeadless" and then nothing, it's likely a browser launch issue. If it says "Executed 0 of 0" and then hangs, it might be a connection issue. If it says "Executed 5 of 10" and then hangs, it's a test execution issue.
Is there a way to set a global timeout for all tests?
Yes, you can set client: { jasmine: { timeoutInterval: 10000 } } in karma.conf.js for Jasmine. This will fail tests that take longer than 10 seconds instead of hanging.