Minimal code to use Istanbul programmatically

*爱你&永不变心* 提交于 2019-12-03 14:35:40

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.

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