Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
npm i -D istanbul-instrumenter-loader
##
Structure
├─ src
│ |– components
│ | |– bar
│ | │ |─ index.js
│ | |– foo/
│ |– index.js
|– test
| |– src
| | |– components
| | | |– foo
| | | | |– index.js
To create a code coverage report for all components (even for those for which you have no tests yet) you have to require all the 1) sources and 2) tests. Something like it's described in "alternative usage" of karma-webpack
test/index.js
// requires all tests in `project/test/src/components/**/index.js`
const tests = require.context('./src/components/', true, /index\.js$/);
tests.keys().forEach(tests);
// requires all components in `project/src/components/**/index.js`
const components = require.context('../src/components/', true, /index\.js$/);
components.keys().forEach(components);
ℹ️ This file will be the only
entry
point forkarma
karma.conf.js
config.set({
...
files: [
'test/index.js'
],
preprocessors: {
'test/index.js': 'webpack'
},
webpack: {
...
module: {
rules: [
// instrument only testing sources with 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$/,
}
The loader supports all options supported by istanbul-lib-instrument
debug
{Boolean}
false
compact
{Boolean}
true
autoWrap
{Boolean}
false
true
to allow return statements outside of functions
esModules
{Boolean}
false
true
to instrument ES2015 Modules
coverageVariable
{String}
__coverage__
preserveComments
{Boolean}
false
output
produceSourceMap
{Boolean}
false
true
to produce a source map for the instrumented code
sourceMapUrlCallback
{Function}
null
webpack.config.js
{
test: /\.js$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: {...options}
}
}
Kir Belevich |
|
|
|
|