You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular15项目Karma单元测试Chrome Headless超时断开问题求助

Angular 15 单元测试无头Chrome频繁断开问题解决

问题描述

基于Angular 15的项目使用Jasmine和Karma执行单元测试时,频繁出现如下错误:

Chrome Headless 115.0.5790.110 (Windows 10) ERROR | Disconnected, because no message in 1000000ms

测试偶尔能正常运行,但多数情况报错,暂未找到有效解决办法。

现有配置信息

karma.conf.js

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['parallel', 'jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-parallel'),
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-coverage'),
      require('@angular-devkit/build-angular/plugins/karma'),
      require('karma-spec-reporter'),
    ],
    parallelOptions: {
      executors: 4, // Defaults to cpu-count - 1
      shardStrategy: 'round-robin'
    },
    client: {
      clearContext: false, // leave Jasmine Spec Runner output visible in browser
      jasmine: {
        random: false
      },
      captureConsole: false
    },
    jasmineHtmlReporter: {
      suppressAll: true // removes the duplicated traces
    },
    coverageReporter: {
      dir: require('path').join(__dirname, './coverage'),
      subdir: '.',
      reporters: [
        { type: 'html' },
        { type: 'text-summary' },
        { type : 'lcovonly'}
      ]
    },
    
    reporters: ["spec"],
    specReporter: {
      maxLogLines: 5,             // limit number of lines logged per test
      suppressSummary: false,      // do not print summary
      suppressErrorSummary: false, // do not print error summary
      suppressFailed: false,      // do not print information about failed tests
      suppressPassed: false,      // do not print information about passed tests
      suppressSkipped: true,      // do not print information about skipped tests
      showBrowser: false,         // print the browser for each spec
      showSpecTiming: true,      // print the time elapsed for each spec
      failFast: false             // test would finish with error when a first fail occurs
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_DISABLE,
    autoWatch: true,
    browsers: ['ChromeHeadless'],
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 3,
    singleRun: true,
    restartOnFileChange: true,
    browserNoActivityTimeout: 1000000
  });
};

test.ts

import 'zone.js';
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
  { teardown: { destroyAfterEach: false }},
);

package.json 依赖片段

"@types/jasmine": "^4.3.2",
"jasmine-core": "~3.10.1",
"karma": "~6.3.9",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.1.0",
"karma-jasmine": "~4.0.1",
"karma-parallel": "^0.3.1"

解决方案

以下是同场景开发者验证有效的解决方法,可逐一尝试:

  • 添加Chrome Headless启动参数
    在karma.conf.js中自定义ChromeHeadless启动配置,解决资源限制或渲染问题:

    browsers: ['ChromeHeadlessCustom'],
    customLaunchers: {
      ChromeHeadlessCustom: {
        base: 'ChromeHeadless',
        flags: [
          '--no-sandbox',
          '--disable-gpu',
          '--disable-dev-shm-usage',
          '--disable-web-security'
        ]
      }
    },
    

    --disable-dev-shm-usage可解决共享内存不足导致的进程崩溃,--no-sandbox规避权限限制

  • 减少并行执行进程数
    当前配置的executors=4可能超出机器资源承载上限,尝试降低数量:

    parallelOptions: {
      executors: 2,
      shardStrategy: 'round-robin'
    },
    
  • 启用测试用例后资源销毁
    修改test.ts中的销毁策略,确保每个测试后释放组件内存:

    getTestBed().initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting(),
      { teardown: { destroyAfterEach: true }},
    );
    
  • 升级依赖版本
    当前依赖版本较旧,存在兼容性问题,升级到适配Angular 15的版本:

    "@types/jasmine": "^4.3.6",
    "jasmine-core": "~4.6.0",
    "karma": "~6.4.2",
    "karma-chrome-launcher": "~3.2.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-parallel": "^0.3.1"
    

    执行npm install完成依赖更新

  • 调整超时参数
    优化超时相关配置,给测试足够的执行时间:

    browserDisconnectTimeout: 30000,
    browserDisconnectTolerance: 2,
    browserNoActivityTimeout: 1200000
    

内容的提问来源于stack exchange,提问作者Arup Karan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 09:55:56