收集代码覆盖率


🌐 Collecting code coverage

当使用 --experimental-test-coverage 命令行标志启动 Node.js 时,会收集代码覆盖率,并在所有测试完成后生成统计数据。如果使用 NODE_V8_COVERAGE 环境变量指定代码覆盖率目录,生成的 V8 覆盖率文件将写入该目录。Node.js 核心模块和 node_modules/ 目录中的文件不会包含在覆盖率报告中。如果启用了覆盖率,覆盖率报告将通过 'test:coverage' 事件发送到任何 测试报告器

🌐 When Node.js is started with the --experimental-test-coverage command-line flag, code coverage is collected and statistics are reported once all tests have completed. If the NODE_V8_COVERAGE environment variable is used to specify a code coverage directory, the generated V8 coverage files are written to that directory. Node.js core modules and files within node_modules/ directories are not included in the coverage report. If coverage is enabled, the coverage report is sent to any test reporters via the 'test:coverage' event.

可以使用以下注释语法在一系列行上禁用覆盖:

🌐 Coverage can be disabled on a series of lines using the following comment syntax:

/* node:coverage disable */
if (anAlwaysFalseCondition) {
  // Code in this branch will never be executed, but the lines are ignored for
  // coverage purposes. All lines following the 'disable' comment are ignored
  // until a corresponding 'enable' comment is encountered.
  console.log('this is never executed');
}
/* node:coverage enable */ 

覆盖也可以针对指定行数禁用。在指定行数之后,覆盖将自动重新启用。如果没有明确提供行数,则仅忽略一行。

🌐 Coverage can also be disabled for a specified number of lines. After the specified number of lines, coverage will be automatically reenabled. If the number of lines is not explicitly provided, a single line is ignored.

/* node:coverage ignore next */
if (anAlwaysFalseCondition) { console.log('this is never executed'); }

/* node:coverage ignore next 3 */
if (anAlwaysFalseCondition) {
  console.log('this is never executed');
} 

测试运行器的代码覆盖功能存在以下限制,这些限制将在未来的 Node.js 版本中解决:

🌐 The test runner's code coverage functionality has the following limitations, which will be addressed in a future Node.js release:

  • 不支持源映射。
  • 不支持从覆盖率报告中排除特定文件或目录。