Prevent Headless Chrome Disconnects in Large Test Suites
In this article
Headless Chrome disconnects during large test suites are usually caused by resource exhaustion, timeouts, or improper session handling. This guide provides practical steps to keep your tests stable and avoid frustrating mid-suite crashes.
What You'll Need
- A test runner (e.g., Jest, Mocha, Playwright, or Selenium) that launches headless Chrome.
- Access to your test configuration files (e.g., jest.config.js, playwright.config.js, or a Selenium WebDriver setup).
- Basic familiarity with command-line tools and your CI/CD pipeline (if applicable).
Step-by-Step
- Increase the browser's timeout settings. Headless Chrome has default timeouts that are too short for long-running tests. In your test configuration, set a generous timeout for page loads, script execution, and network requests. For example, in Playwright:
use: { timeout: 60000 }. In Selenium:driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS). - Disable Chrome's automatic resource throttling. Headless Chrome may throttle timers and animations in background tabs. Add the flag
--disable-background-timer-throttlingand--disable-backgrounding-occluded-windowsto your Chrome launch arguments. This prevents the browser from slowing down when it thinks the tab is not visible. - Limit the number of concurrent tabs or pages. Running too many parallel tests in the same browser instance can overwhelm it. Use a single page per test, and close pages after each test. In Playwright, use
test.afterEach(async () => { await page.close(); }). - Manage memory usage. Large suites can cause memory leaks. Set a memory limit for the Chrome process using
--js-flags="--max-old-space-size=4096"(adjust the number based on your available RAM). Also, periodically restart the browser between test files or groups. - Use a dedicated browser instance per worker. If your test runner supports parallel workers, ensure each worker gets its own Chrome instance. In Playwright, set
workers: 1or a number that matches your CPU cores. In Jest with Puppeteer, usebrowser = await puppeteer.launch()inside each test file. - Add retry logic for flaky disconnects. Even with optimizations, occasional disconnects happen. Configure your test runner to retry failed tests. In Playwright:
retries: 2. In Jest:jest.retryTimes(2). - Set a longer graceful shutdown timeout. When a test suite ends, Chrome may take time to close. Increase the browser's close timeout to avoid abrupt kills. In Playwright, set
timeoutinuseto 120000. In Selenium, calldriver.quit()and add a small delay before the process exits. - Monitor system resources. During the suite, watch CPU and memory usage. If you see spikes, reduce parallelism or add a small delay between tests. Use tools like
toporpson Linux, or Task Manager on Windows.
Common Mistakes
- Using too many concurrent workers. Each Chrome instance consumes significant memory. Running 10 workers on a 4GB machine will cause disconnects. Start with 1 worker and scale up gradually.
- Ignoring the browser's default timeouts. Many test frameworks have a default timeout of 30 seconds. If your tests take longer, they will fail with a disconnect error. Always set explicit timeouts.
- Not closing pages or browsers. Leaving pages open accumulates memory. Always close pages after each test and close the browser after the suite.
- Using the same browser instance across tests without cleanup. This can lead to session state leaking and unexpected disconnects. Create a fresh browser context for each test.
Tips
- Use the
--no-sandboxflag only in Docker or CI environments, as it reduces security but can prevent certain crashes. - In Playwright, use
context = await browser.newContext()for each test to isolate sessions. - For Selenium, consider using a remote WebDriver (like Selenium Grid) to distribute load, but ensure the network connection is stable.
- Keep your Chrome version updated, as newer versions often fix memory leaks and stability issues.
- If using Puppeteer, set
args: ['--disable-dev-shm-usage']to avoid /dev/shm issues in Docker containers.
Troubleshooting
If disconnects still occur:
- Check the error message. If it says "Target closed" or "Session expired," it's likely a timeout issue. Increase timeouts further.
- Look for memory-related errors. If you see "Out of memory" or "Chrome crashed," reduce the number of workers and add memory limits.
- Test with a single test. Run one test in isolation. If it passes, the issue is resource exhaustion. If it fails, the problem is in your test code.
- Enable verbose logging. Run Chrome with
--enable-logging --v=1to get detailed logs. This can reveal network or rendering issues. - Try headed mode. Temporarily run Chrome in headed mode to see if the issue is specific to headless. Some features like WebGL may behave differently.
Frequently Asked Questions
Why does headless Chrome disconnect after a few tests?
Most often it's due to memory leaks or running out of file descriptors. Restart the browser periodically and close pages after each test.
Can I use a single Chrome instance for all tests?
Yes, but it's risky. You must ensure no state leaks between tests. It's safer to use a new context or page per test.
What is the best timeout setting for headless Chrome?
There's no one-size-fits-all. Start with 60 seconds and increase if your tests are slower. Monitor your test durations to find the right value.
Does disabling background throttling help?
Yes, it prevents Chrome from slowing down timers in headless mode, which can cause tests to hang or disconnect.
Should I use a headless browser at all for large suites?
Yes, headless is more resource-efficient than headed mode. But you need proper configuration to avoid disconnects. If problems persist, consider using a browser farm service.
How do I handle disconnects in CI pipelines?
Add retry logic and ensure your CI environment has enough memory. Also, set a global timeout for the entire suite to avoid hanging.