开玩笑报道:如何获得总报道百分比?

Jest coverage: How can I get a total percentage of coverage?

在我的 gitlab 管道中,我想将总百分比值发送到服务器。但是 jest --coverage 只给我 /coverage 中的这些大型报告文件。我似乎无法解析它的总价值。我是否缺少参数?

Jest 内部正在使用 Istanbul.js 报告覆盖率,您可以修改 Jest's configuration with CLI arg to "text-summary" or any other alternative reporter

jest --coverageReporters="text-summary"

text-summary output:

=============================== Coverage summary ===============================
Statements   : 100% ( 166/166 )
Branches     : 75% ( 18/24 )
Functions    : 100% ( 49/49 )
Lines        : 100% ( 161/161 )
================================================================================

或者你可以自己写记者。

感谢 Teneff 的回答,我选择了 coverageReporter="json-summary"。

 jest --coverage --coverageReporters="json-summary" 

这会生成一个可以轻松解析的覆盖率-summary.json 文件。我直接从 json:

得到总值
  "total": {
    "lines": { "total": 21777, "covered": 65, "skipped": 0, "pct": 0.3 },
    "statements": { "total": 24163, "covered": 72, "skipped": 0, "pct": 0.3 },
    "functions": { "total": 5451, "covered": 16, "skipped": 0, "pct": 0.29 },
    "branches": { "total": 6178, "covered": 10, "skipped": 0, "pct": 0.16 }
  }

我自己需要这个,所以我创建了一个自定义报告器。您需要在 coverageReporters 中启用 json-summary 报告器,然后您可以使用此自定义报告器来显示总数:

const { readFile } = require('fs');
const { join } = require('path');

// Gitlab Regex: Total Coverage: (\d+\.\d+ \%)
module.exports = class CoverageReporter {
  constructor(globalConfig) {
    this.globalConfig = globalConfig;
    this.jsonSummary = join(this.globalConfig.coverageDirectory, 'coverage-summary.json');
  }
  async onRunComplete() {
    const coverage = require(this.jsonSummary);
    const totalSum = ['lines', 'statements', 'functions', 'branches']
      .map(i => coverage.total[i].pct)
      .reduce((a, b) => a + b, 0)
    const avgCoverage = totalSum / 4
    console.debug()
    console.debug('========= Total Coverage ============')
    console.debug(`Total Coverage: ${avgCoverage.toFixed(2)} %`)
    console.debug('=======================================')
  }
}