问题
I want to execute the command
istanbul cover node_modules/mocha/bin/_mocha dist/test
using the Istanbul programmatic API. But the docs don't say much about it, besides that everything is possible and linking to the enormous API documentation. I couldn't find any short example on the internet. I do not want to spawn a child process or use another module from NPM. I know how to run Mocha programmatically without coverage, so that is not the problem.
回答1:
I figured out one way to do this, but it isn't too pretty. If you eval
(I know!) the instrumented code, Istanbul writes the coverage object to the global variable __coverage__
. You can also specify the name of the global variable in the constructor for the instrumenter if you like. Here is a command line script shows how it can be done:
const istanbul = require('istanbul');
const instrumenter = new istanbul.Instrumenter();
const collector = new istanbul.Collector();
const fs = require('fs');
const filename = 'file.js';
fs.readFile(filename, 'utf-8', (err, data) => {
instrumenter.instrument(data, filename, (err, generatedCode) => {
eval(generatedCode);
console.log(JSON.stringify(global['__coverage__']));
});
});
The file part and the console.log
are just to make a complete demo. All you really need is instrument
and eval
. Whether you would use eval
yourself here is up to you.
来源:https://stackoverflow.com/questions/39302198/minimal-code-to-use-istanbul-programmatically