【问题标题】:Jest coverage: How can I get a total percentage of coverage?开玩笑覆盖率:我怎样才能获得覆盖率的总百分比?
【发布时间】:2020-07-13 00:09:29
【问题描述】:

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

【问题讨论】:

  • 阅读文档后,我认为 Jest 不能简单地给你百分比而不使用报告作为文件。我建议您编写一个 js 脚本来读取您的索引文件并使用该值执行任何您想要的操作,然后配置您的管道以在开玩笑测试之后立即执行此脚本。您也可以绕过阈值:stackoverflow.com/questions/40794031/…

标签: jestjs code-coverage


【解决方案1】:

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

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

这会生成一个易于解析的 coverage-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 }
  }

【讨论】:

    【解决方案2】:

    内部开玩笑是使用 Istanbul.js 报告覆盖率,您可以使用 CLI arg 将 Jest's configuration 修改为“text-summary”或任何其他 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 )
    ================================================================================
    

    或者你可以写自己的记者。

    【讨论】:

    • summary 是关键字 ;) 谢谢!
    【解决方案3】:

    我自己也需要这个,所以我创建了一个自定义记者。您需要在 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('=======================================')
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-09
      • 2017-07-15
      • 2017-07-31
      • 1970-01-01
      • 2022-11-09
      • 2018-05-29
      • 1970-01-01
      相关资源
      最近更新 更多