Skip to content

Instantly share code, notes, and snippets.

@rundef
Last active December 22, 2020 16:45
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rundef/22545366591d73330a48b8948fa060a7 to your computer and use it in GitHub Desktop.
Save rundef/22545366591d73330a48b8948fa060a7 to your computer and use it in GitHub Desktop.
Script to merge multiple nyc/istanbul code coverage json reports into a single html report: http://rundef.com/typescript-code-coverage-istanbul-nyc
var path = require('path'),
fs = require('fs'),
libCoverage = require('nyc/node_modules/istanbul-lib-coverage'),
libReport = require('nyc/node_modules/istanbul-lib-report'),
reports = require('nyc/node_modules/istanbul-reports');
var rootFolder = __dirname;
var mergeIntoFolder = 'final';
var files = fs.readdirSync(rootFolder);
var mergedCoverageMap = null;
for(var i = 0; i < files.length; i++) {
var fullPath = path.resolve(rootFolder, files[i]);
if(files[i] !== mergeIntoFolder && fs.statSync(fullPath).isDirectory()) {
fullPath = path.resolve(fullPath, 'coverage-final.json');
var map = libCoverage.createCoverageMap(JSON.parse(fs.readFileSync(fullPath, 'utf8')));
if (mergedCoverageMap !== null) {
mergedCoverageMap.merge(map);
}
else {
mergedCoverageMap = map;
}
}
}
var context = libReport.createContext({
dir: path.join(rootFolder, mergeIntoFolder)
});
tree = libReport.summarizers.pkg(mergedCoverageMap);
tree.visit(reports.create('html'), context);
fs.writeFileSync(path.join(rootFolder, '..', '..', '.nyc_output', 'coverage-final.json'), JSON.stringify(mergedCoverageMap.toJSON()));
@supnate
Copy link

supnate commented Aug 24, 2016

Thanks @rundef for providing the gist. I finally merged reports using a different approach using below npm scripts:

"nyc-report": "nyc report --reporter=lcov --reporter=text",
"test": "npm run test:cli && node test/cache_nyc_output.js && npm run test:app && node test/cp_back_nyc_output.js && npm run nyc-report",

nyc report reads data from .nyc_output folder but each time run nyc clears the folder. So I wrote scripts to cache nyc_output and copy them back when all tests done. Then run nyc report to generate the final report.

@thirusabari
Copy link

hai @rundef . In my project, i had used jasmine framework. Could you please tell me, how to implement the same for javascript?

@simlu
Copy link

simlu commented Apr 4, 2018

This was a great help for recursively generating coverage reports using nyc and mocha programmatically. Thank you!

@osher
Copy link

osher commented Jul 2, 2018

@supnate - you could also use the --temp-directory flag, wich lets you specify where the output is written.

@jasonk
Copy link

jasonk commented Oct 2, 2020

You can also just use nyc --no-clean to prevent it from clearing out .nyc_output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment