Minimal code to use Istanbul programmatically

我的梦境 提交于 2020-01-22 20:16:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!