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

Angular测试添加--code-coverage时出现Karma加载错误求助

Angular测试添加--code-coverage参数时触发"load error"问题

执行ng test --no-watch --code-coverage命令时持续出现"load error"错误,但不带--code-coverage参数运行ng test完全正常。

Karma配置文件(karma.conf.js)

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: { clearContext: false },
    coverageReporter: {
      dir: require('path').join(__dirname, '../coverage/DATAGERRYApp'),
      reporters: [{ type: 'html' }, { type: 'lcovonly' }, { type: 'text-summary' }],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG, // Enabled for detailed logging
    autoWatch: true,
    browsers: ['ChromeHeadless'],
    singleRun: true,
    restartOnFileChange: true
  });
};

使用的命令

ng test --no-watch --code-coverage

错误输出

Error: Found 1 load error
    at Server.<anonymous> (/path/to/project/node_modules/karma/lib/server.js:243:26)

已尝试的解决步骤

  • 清理node_modules并重新安装依赖
  • 修改karma.conf.js,用karma-coverage替代karma-coverage-istanbul-reporter
  • 执行ng build --configuration test检查循环依赖
  • 执行ng cache clean清理Angular缓存

可能的解决方案

  1. 检查coverage目录权限与路径
    确保配置中coverageReporter.dir指定的路径存在且当前用户有读写权限,可尝试手动创建../coverage/DATAGERRYApp目录后再执行命令。

  2. 解决参数冲突
    配置中singleRun: true与命令行--no-watch功能重复,可尝试将karma.conf.js中的singleRun改为false,或者去掉命令行的--no-watch参数,避免配置与命令行参数冲突导致加载异常。

  3. 查看详细错误日志
    当前错误日志过于简略,可尝试在命令中添加--verbose参数,或者查看Karma的完整日志输出,定位具体的加载错误源(比如某个测试文件、依赖库加载失败)。

  4. 调整浏览器配置
    暂时将browsers改为['Chrome']而非ChromeHeadless,运行测试查看是否能正常生成覆盖率,排除Headless模式下的环境问题。

  5. 检查测试文件语法与依赖
    逐个排查测试文件,确认是否存在语法错误、未正确导入的依赖,或者测试文件中引用了未在测试环境中加载的模块,这类问题在生成覆盖率时可能触发加载错误。

  6. 验证karma-coverage版本兼容性
    确保karma-coverage版本与当前Angular CLI、Karma版本兼容,可查看项目package.json中的依赖版本,尝试降级或升级karma-coverage到匹配的版本。

内容的提问来源于stack exchange,提问作者Abdullah Khalid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 18:40:03