NX中Karma覆盖率未达标时构建不失败,如何令测试命令报错?
问题场景
在Angular项目中使用NRWL NX,CI环境执行单元测试命令如下:nx affected:test --base=main --watch=false --browsers=ChromeHeadlessNoSandbox --codeCoverage --parallel=true --maxParallel=4
当代码覆盖率未达到预设阈值时,构建仍正常通过,尽管日志中明确输出覆盖率错误:
07 12 2022 16:06:14.750:ERROR [coverage]: Chrome Headless 106.0.5249.91 (Linux x86_64): Coverage for branches (99.68%) does not meet global threshold (100%)
单独运行单个项目测试也存在相同问题:nx run one-single-project:test --watch=false --browsers=ChromeHeadlessNoSandbox --codeCoverage=true
执行后echo $?返回值为0(表示命令执行成功),但实际应返回错误码终止CI流程。
解决方法
针对Karma配置(适用于使用Karma作为测试运行器的项目)
NX集成Karma时,默认不会因覆盖率不达标终止命令,需手动开启failOnError配置:
- 打开目标项目的
karma.conf.js(或karma.conf.ts)配置文件 - 在
coverageIstanbulReporter配置块中添加failOnError: true:
coverageIstanbulReporter: { dir: require('path').join(__dirname, '../../coverage/your-project-name'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true, thresholds: { global: { statements: 100, lines: 100, branches: 100, functions: 100 } }, failOnError: true // 核心配置:覆盖率不达标时触发命令失败 }
针对Jest配置(适用于使用Jest作为测试运行器的项目)
若项目使用Jest作为测试运行器,需确保jest.config.ts中配置了coverageThreshold,Jest默认会在覆盖率不达标时返回错误码:
export default { // 其他Jest配置 coverageThreshold: { global: { branches: 100, functions: 100, lines: 100, statements: 100 } }, // 若仍未生效,可显式开启failOnError failOnError: true };
项目级全局配置(可选)
也可在项目根目录的project.json中修改测试目标的配置,统一生效:
{ "targets": { "test": { "executor": "@nrwl/jest:jest", "options": { "jestConfig": "your-project-name/jest.config.ts", "codeCoverage": true, "coverageThreshold": { "global": { "branches": 100, "lines": 100, "statements": 100, "functions": 100 } }, "failOnError": true } } } }
内容的提问来源于stack exchange,提问作者Francesco Borzi

