'Jest coverage: How can I get a total percentage of coverage?
In my gitlab pipeline I want to send the total percentage value to a server. But jest --coverage only gives me these large reporting files in /coverage. I can't seem to parse the total value out of it. Am I missing a parameter?
Solution 1:[1]
Thank's to Teneff's answer, I go with the coverageReporter="json-summary".
jest --coverage --coverageReporters="json-summary"
This generates a coverage-summary.json file which can easily be parsed. I get the total values directly from the 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 }
}
Solution 2:[2]
Internally jest is using Istanbul.js to report coverage and you can modify 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 )
================================================================================
Or you can write your own reporter.
Solution 3:[3]
I needed this myself, so I created a custom reporter. You need the json-summary reporter enabled in coverageReporters and then you can use this custom reporter to show the total:
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('=======================================')
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | L. Heider |
| Solution 2 | |
| Solution 3 | codewandler |
