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?
Code Coverage Percentage = (Number of lines of code executed by a testing algorithm/Total number of lines of code in a system component) * 100.
To get Jest up & running, install it as a dev dependency in your project. For ease of use, also in your CI/CD pipelines, I recommend to add script entries for running Jest with and without collecting coverage statistics in your package.
Jest: Coverage Report. Popular JavaScript frameworks can use Facebook's Jest to perform unit tests. Jest has the Coverage Report feature that allows us to check if our code covers all lines of the files we choose by generating an HTML file that we can open.
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 } }
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.
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('=======================================')
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With