收集代码覆盖率


【Collecting code coverage】

稳定性: 1 - 实验性

当使用 --experimental-test-coverage 命令行标志启动 Node.js 时,将收集代码覆盖率,并在所有测试完成后报告统计信息。如果使用 NODE_V8_COVERAGE 环境变量指定代码覆盖率目录,生成的 V8 覆盖文件将写入该目录。默认情况下,Node.js 核心模块和 node_modules/ 目录下的文件不会包含在覆盖率报告中。但是,可以通过 --test-coverage-include 标志显式包含它们。如果启用了覆盖率,覆盖率报告将通过 '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, by default, not included in the coverage report. However, they can be explicitly included via the --test-coverage-include flag. 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');
}