Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@supnate 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

This comment has been minimized.

Copy link

@thirusabari thirusabari commented Oct 23, 2017

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

@simlu

This comment has been minimized.

Copy link

@simlu simlu commented Apr 4, 2018

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

@osher

This comment has been minimized.

Copy link

@osher osher commented Jul 2, 2018

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

@jasonk

This comment has been minimized.

Copy link

@jasonk 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