Collecting code coverage


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

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

/* 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 */

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

/* 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 版本中解决:

  • 虽然为子进程收集了覆盖率数据,但此信息未包含在覆盖率报告中。 因为命令行测试运行器使用子进程来执行测试文件,所以不能与 --experimental-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');
}

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

  • Although coverage data is collected for child processes, this information is not included in the coverage report. Because the command line test runner uses child processes to execute test files, it cannot be used with --experimental-test-coverage.
  • Source maps are not supported.
  • Excluding specific files or directories from the coverage report is not supported.