webpack-mocha-plugin
Webpack plugin integration with mocha testing framework + coverage with istanbul.

Installation
npm i -D webpack-mocha-plugin mocha istanbul remap-istanbul
Webpack Config
This webpack configuration will run your tests and write a html and json coverage report to
coverage
, after webpack compiles the project. If webpack is in watch mode tests are run after
each compilation.
You can configure entry and output how ever you like. The plugin will add all generated files
ending in .js
to the mocha test.
const WebpackMochaPlugin = require('webpack-mocha-plugin');
const nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'node',
entry: {
test: __dirname + '/test.bundle.ts'
},
output: {
path: '.tmp/test',
filename: '[name].bundle.js'
},
resolve: {
extensions: ['.ts', '.js']
},
externals: [nodeExternals()],
devtool: 'inline-source-map',
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map'
},
{
test: /\.ts$/,
loader: 'awesome-typescript'
},
{
enforce: 'post',
test: /\.(js|ts)$/,
exclude: /\.(spec)\.(ts|js)$/,
loader: 'sourcemap-istanbul-instrumenter',
query: {
'force-sourcemap': true
}
}
]
},
plugins: [
new WebpackMochaPlugin({
codeCoverage: true
})
],
watchOptions: {
ignored: /coverage/
}
};
Options
new WebpackMochaPlugin({
mocha?: any = {};
codeCoverage?: boolean = false;
coverageVariable?: string = '__coverage__';
coverageReports?: string[] = ['html', 'json'];
coverageDir?: string = 'coverage';
})
You can pass all options which the Mocha JS API takes in mocha
.
codeCoverage
enables or disables generation of a report.
coverageVariable
is where the instrumenter puts the coverage information.
coverageReports
takes all reporters which istanbul
can generate.
coverageDir
is the directory where the coverage report will be stored.
Test Bundle
const ctx = require.context('src', true, /\.(spec)\.js/)
ctx.keys().map(moduleId => ctx(moduleId))
const ctx = require.context('src', true, /\.js/)
ctx.keys().map(moduleId => ctx(moduleId))