Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
npm i -D istanbul-instrumenter-loader
结构
├─ src
│ |– components
│ | |– bar
│ | │ |─ index.js
│ | |– foo/
│ |– index.js
|– test
| |– src
| | |– components
| | | |– foo
| | | | |– index.js
为生成所有组件(包括你没写测试的那些)的代码覆盖率报告,你需要 require 所有业务和测试的代码。相关内容在 karma-webpack 其他用法中有涉及
test/index.js
// requires 所有在 `project/test/src/components/**/index.js` 中的测试
const tests = require.context('./src/components/', true, /index\.js$/);
tests.keys().forEach(tests);
// requires 所有在 `project/src/components/**/index.js` 中的组件
const components = require.context('../src/components/', true, /index\.js$/);
components.keys().forEach(components);
ℹ️ 以下为
karma
的唯一入口
起点文件
karma.conf.js
config.set({
...
files: [
'test/index.js'
],
preprocessors: {
'test/index.js': 'webpack'
},
webpack: {
...
module: {
rules: [
// 用 Istanbul 只监测业务代码
{
test: /\.js$/,
use: { loader: 'istanbul-instrumenter-loader' },
include: path.resolve('src/components/')
}
]
}
...
},
reporters: [ 'progress', 'coverage-istanbul' ],
coverageIstanbulReporter: {
reports: [ 'text-summary' ],
fixWebpackSourcePaths: true
}
...
});
Babel
You must run the instrumentation as a post step
webpack.config.js
{
test: /\.js$|\.jsx$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: { esModules: true }
},
enforce: 'post',
exclude: /node_modules|\.spec\.js$/,
}
此 loader 支持 istanbul-lib-instrument
的所有配置选项
Name | Type | Default | Description |
---|---|---|---|
debug |
{Boolean} |
false |
Turn on debugging mode |
compact |
{Boolean} |
true |
Generate compact code |
autoWrap |
{Boolean} |
false |
Set to true to allow return statements outside of functions |
esModules |
{Boolean} |
false |
Set to true to instrument ES2015 Modules |
coverageVariable |
{String} |
__coverage__ |
Name of global coverage variable |
preserveComments |
{Boolean} |
false |
Preserve comments in output |
produceSourceMap |
{Boolean} |
false |
Set to true to produce a source map for the instrumented code |
sourceMapUrlCallback |
{Function} |
null |
A callback function that is called when a source map URL is found in the original code. This function is called with the source filename and the source map URL |
webpack.config.js
{
test: /\.js$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: {...options}
}
}
Kir Belevich | Juho Vepsäläinen | Joshua Wiens | Michael Ciniawsky | Matt Lewis |