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

配置package.json中nyc配置后,nyc + mocha仍无法生成覆盖率报告且报错的问题排查

解决nyc + mocha测试通过但覆盖率为0的问题

首先,从你的配置和输出来看,主要有几个核心问题需要调整,咱们一步步来排查:

1. 错误的include路径是覆盖率为0的关键

你的nyc配置里include指向的是测试文件(test/**/*.*.[tj]s?(x)),但nyc需要统计的是业务源代码的覆盖率,而不是测试代码本身!这直接导致nyc找不到需要统计的目标文件,所以所有覆盖率指标都显示为0。

你需要把include修改为你的源代码路径:

  • 如果源码都在src/目录下,改成:
    "include": [
      "src/**/*.[tj]s?(x)"
    ]
    
  • 如果源码在项目根目录(比如app.ts),可以搭配exclude明确排除无关文件:
    "include": [
      "*.ts",
      "**/*.ts"
    ],
    "exclude": [
      "test/**/*",
      "node_modules/**/*"
    ]
    

2. ESM模块兼容性问题

你的start脚本用了ts-node-esm(说明项目是ESM模块),但test脚本用的是ts-node/register(CommonJS的注册器),这会导致nyc的代码插桩(instrumentation)无法正确处理ESM模块,进而影响覆盖率统计。

修改你的test脚本,改用ESM兼容的加载方式:

"scripts": {
  "test": "NODE_ENV='test' nyc --require ts-node/register/esm mocha 'test/**/*.*.*.ts' --exit"
}

另外,确保你的package.json中已经添加了"type": "module"(ESM项目必备配置)。

3. runner.once is not a function错误:版本兼容问题

这个错误通常是nyc和mocha的版本不匹配导致的——旧版本的nyc无法兼容新版本mocha的API。

解决方法:

  • 升级nyc到最新稳定版:npm install nyc@latest --save-dev
  • 同步升级@istanbuljs/nyc-config-typescript,确保和nyc版本兼容:npm install @istanbuljs/nyc-config-typescript@latest --save-dev

修改后的完整package.json示例

{
  "name": "open-concepts",
  "version": "1.0.0",
  "description": "Simply matching idea makers and doers",
  "main": "app.js",
  "type": "module",
  "scripts": {
    "start": "nodemon --watch './**/*.ts' --exec 'ts-node-esm' app.ts",
    "test": "NODE_ENV='test' nyc --require ts-node/register/esm mocha 'test/**/*.*.*.ts' --exit"
  },
  "nyc": {
    "extends": "@istanbuljs/nyc-config-typescript",
    "check-coverage": true,
    "all": true,
    "include": [
      "src/**/*.[tj]s?(x)" // 替换为你的实际源代码路径
    ],
    "exclude": [
      "test/**/*",
      "node_modules/**/*"
    ],
    "reporter": [
      "html",
      "lcov",
      "text",
      "text-summary",
      "cobertura"
    ],
    "report-dir": "coverage"
  }
}

最后一步:清理缓存重新测试

运行测试前先删除旧的coverage目录,避免缓存影响结果:

rm -rf coverage && npm test

这样调整后,应该就能正常生成符合预期的覆盖率报告了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 13:22:31