我最近也遇到了同样的问题。我在我的项目中有一个解决方案
angular-require-lazy,我将进行描述。虽然需要大量自定义内容,但最终它能够正常工作。
概要
- 预先仪器化您的代码,保持基线
- 使Karma服务器发送预先仪器化的源文件
- 使用考虑基线的报告生成器收集覆盖结果
1. 预先仪器化
首先,我没有成功使用coverage
预处理器。由于RequireJS动态加载源文件,现有的预处理器不足以满足我们的需求。相反,我首先使用伊斯坦布尔手动运行仪器化阶段,使用自定义的Grunt插件:
(在此处查看 here)
module.exports = function(grunt) {
grunt.registerMultiTask("instrument", "Instrument with istanbul", function() {
var istanbul = require("istanbul"),
instrumenter,
options,
instrumenterOptions,
baselineCollector;
options = this.options({
});
if( options.baseline ) {
baselineCollector = new istanbul.Collector();
}
instrumenterOptions = {
coverageVariable: options.coverageVariable || "__coverage__",
embedSource: options.embedSource || false,
preserveComments: options.preserveComments || false,
noCompact: options.noCompact || false,
noAutoWrap: options.noAutoWrap || false,
codeGenerationOptions: options.codeGenerationOptions,
debug: options.debug || false,
walkDebug: options.walkDebug || false
};
instrumenter = new istanbul.Instrumenter(instrumenterOptions);
this.files.forEach(function(f) {
if( f.src.length !== 1 ) {
throw new Error("encountered src with length: " + f.src.length + ": " + JSON.stringify(f.src));
}
var filename = f.src[0],
code = grunt.file.read(filename, {encoding: grunt.file.defaultEncoding}),
result = instrumenter.instrumentSync(code, filename),
baseline,
coverage;
if( options.baseline ) {
baseline = instrumenter.lastFileCoverage();
coverage = {};
coverage[baseline.path] = baseline;
baselineCollector.add(coverage);
}
grunt.file.write(f.dest, result, {encoding: grunt.file.defaultEncoding});
});
if( options.baseline ) {
grunt.file.write(options.baseline, JSON.stringify(baselineCollector.getFinalCoverage()), {encoding: grunt.file.defaultEncoding});
}
});
};
它被用作:
grunt.initConfig({
instrument: {
sources: {
files: [{
expand: true,
cwd: "..the base directory of your sources...",
src: ["...all your sources..."],
dest: "...where to put the instrumented files..."
}],
options: {
baseline: "build-coverage/baseline.json"
}
}
},
...
保留基准线以备后用非常重要。
如果不使用Grunt,我认为您仍然可以从此代码中获得灵感。实际上,Istanbul API非常适合手动操作,因此如果需要,可以使用它。
2. 配置Karma服务器以发送预先插装的文件
首先,配置预处理器以使用您的预先插装的文件(注意我们将使用自定义预处理器和报告生成器,代码位于最后):
...
preprocessors: {
'...all your sources...': 'preInstrumented'
},
preInstrumentedPreprocessor: {
basePath: '!!!SAME AS GRUNT'S dest!!!',
stripPrefix: '...the base prefix to strip, same as Grunt's cwd...'
},
...
3. 调整报告生成器以使用基准线
覆盖率报告生成器必须考虑基准线。不幸的是,原始版本并没有考虑这一点,因此我进行了一些调整。配置如下:
...
reporters: [
'progress', 'coverage'
],
coverageReporter: {
type: 'lcov',
dir: 'build-coverage/report',
baseLine: '!!!SAME AS GRUNT'S options.baseline!!!'
},
...
代码
为了激活我的自定义Karma插件,我包含了以下内容:
plugins: [
...
require('./build-scripts/karma')
],
文件夹./build-scripts/karma
包含以下文件:
index.js:
module.exports = {
"preprocessor:preInstrumented": ["factory", require("./preInstrumentedPreprocessor")],
"reporter:coverage": ["type", require("./reporter")]
};
preInstrumentedPreprocessor.js:
var path = require("path"),
fs = require("fs");
createPreInstrumentedPreprocessor.$inject = ["args", "config.preInstrumentedPreprocessor", "config.basePath", "logger", "helper"];
function createPreInstrumentedPreprocessor(args, config, basePath, logger, helper) {
var STRIP_PREFIX_RE = new RegExp("^" + path.join(basePath, config.stripPrefix).replace(/\\/g, "\\\\"));
function instrumentedFilePath(file) {
return path.join(basePath, config.basePath, path.normalize(file.originalPath).replace(STRIP_PREFIX_RE, ""));
}
return function(content, file, done) {
fs.readFile(instrumentedFilePath(file), {encoding:"utf8"}, function(err, instrumentedContent) {
if( err ) throw err;
done(instrumentedContent);
});
};
}
module.exports = createPreInstrumentedPreprocessor;
reporter.js:
(查看此问题,了解我“fork”它的原因。)
var path = require('path');
var fs = require('fs');
var util = require('util');
var istanbul = require('istanbul');
var dateformat = require('dateformat');
var Store = istanbul.Store;
var BasePathStore = function(opts) {
Store.call(this, opts);
opts = opts || {};
this.basePath = opts.basePath;
this.delegate = Store.create('fslookup');
};
BasePathStore.TYPE = 'basePathlookup';
util.inherits(BasePathStore, Store);
Store.mix(BasePathStore, {
keys : function() {
return this.delegate.keys();
},
toKey : function(key) {
if (key.indexOf('./') === 0) { return path.join(this.basePath, key); }
return key;
},
get : function(key) {
return this.delegate.get(this.toKey(key));
},
hasKey : function(key) {
return this.delegate.hasKey(this.toKey(key));
},
set : function(key, contents) {
return this.delegate.set(this.toKey(key), contents);
}
});
var CoverageReporter = function(rootConfig, helper, logger) {
var log = logger.create('coverage');
var config = rootConfig.coverageReporter || {};
var basePath = rootConfig.basePath;
var reporters = config.reporters;
var baseLine;
if (config.baseLine) {
baseLine = JSON.parse(fs.readFileSync(path.join(basePath, config.baseLine), {encoding:"utf8"}));
}
if (!helper.isDefined(reporters)) {
reporters = [config];
}
this.adapters = [];
var collectors;
var pendingFileWritings = 0;
var fileWritingFinished = function() {};
function writeEnd() {
if (!--pendingFileWritings) {
Object.keys(collectors).forEach(function(key) {
collectors[key].dispose();
});
fileWritingFinished();
}
}
function generateOutputDir(browserName, dir, subdir) {
dir = dir || 'coverage';
subdir = subdir || browserName;
if (typeof subdir === 'function') {
subdir = subdir(browserName);
}
return path.join(dir, subdir);
}
this.onRunStart = function(browsers) {
collectors = Object.create(null);
if (browsers) {
browsers.forEach(function(browser) {
collectors[browser.id] = new istanbul.Collector();
});
}
};
this.onBrowserStart = function(browser) {
var collector = new istanbul.Collector();
if( baseLine ) {
collector.add(baseLine);
}
collectors[browser.id] = collector;
};
this.onBrowserComplete = function(browser, result) {
var collector = collectors[browser.id];
if (!collector) {
return;
}
if (result && result.coverage) {
collector.add(result.coverage);
}
};
this.onSpecComplete = function(browser, result) {
if (result.coverage) {
collectors[browser.id].add(result.coverage);
}
};
this.onRunComplete = function(browsers) {
reporters.forEach(function(reporterConfig) {
browsers.forEach(function(browser) {
var collector = collectors[browser.id];
if (collector) {
pendingFileWritings++;
var outputDir = helper.normalizeWinPath(path.resolve(basePath, generateOutputDir(browser.name,
reporterConfig.dir || config.dir,
reporterConfig.subdir || config.subdir)));
helper.mkdirIfNotExists(outputDir, function() {
log.debug('Writing coverage to %s', outputDir);
var options = helper.merge({}, reporterConfig, {
dir : outputDir,
sourceStore : new BasePathStore({
basePath : basePath
})
});
var reporter = istanbul.Report.create(reporterConfig.type || 'html', options);
try {
reporter.writeReport(collector, true);
} catch (e) {
log.error(e);
}
writeEnd();
});
}
});
});
};
this.onExit = function(done) {
if (pendingFileWritings) {
fileWritingFinished = done;
} else {
done();
}
};
};
CoverageReporter.$inject = ['config', 'helper', 'logger'];
module.exports = CoverageReporter;
我知道这是很多代码。我希望有一个更简单的解决方案(大家有什么想法吗?)。无论如何,您可以通过使用angular-require-lazy来查看其工作原理并进行实验。我希望这能有所帮助...