I am trying to add code coverage to my web project and found that, no matter what I do, my coverage for all files is always 100% for statements, functions, lines, but branches are always 50% (it lies). And that was progress since adding karma-coverage-istanbul-instrumenter. Prior to that addition, it was always 0%.
I created a stand-alone project to demonstrate the issue (deleting karma-coverage-istanbul-instrumenter in karma.conf.js will return it to 0% coverage). It has one file, so arguably, not a great demonstration, but test and branch coverage is definitely 100%.
I did do some debugging in karma, and I found that it looks like when the result event fires, every file has exactly the same coverage. It's unclear which plugin is the issue. I did switch over to jasmine to see if it was "mocha" related, but it's not.
I'm using [email protected], [email protected] [email protected], and the latest of everything.
My karma.config.js file is as follows:
const path = require('path');
const webpackConfig = require('./webpack.config.js');
module.exports = function(config) {
config.set({
restartOnFileChange: true,
logLevel: config.LOG_DEBUG,
colors: true,
singleRun: true,
browsers: [ 'MyHeadlessChrome' ],
customLaunchers: {
MyHeadlessChrome: {
base: 'ChromeHeadless',
flags: [ '--no-sandbox' ]
}
},
frameworks: [
'webpack',
'mocha',
'chai'
],
plugins: [
'karma-webpack',
'karma-mocha',
'karma-chai',
'karma-chrome-launcher',
'karma-sourcemap-loader',
'karma-mocha-reporter',
'karma-coverage-istanbul-reporter',
'karma-coverage-istanbul-instrumenter'
],
files: [
'test/*.spec.js',
'src/*.js'
],
preprocessors: {
'test/*.spec.js': [ 'webpack' ],
'src/*.js': [ 'webpack', 'sourcemap', 'karma-coverage-istanbul-instrumenter' ]
},
reporters: [ 'mocha', 'coverage-istanbul' ],
coverageIstanbulReporter: {
reports: [ 'html', 'lcov', 'text-summary' ],
dir: path.join(__dirname, 'coverage'),
fixWebpackSourcePaths: false,
esModules: false,
// enforce percentage thresholds
// anything under these percentages will cause karma to fail
// with an exit code of 1 if not running in watch mode
thresholds: {
// set to `true` to not fail the test command when thresholds are not met
emitWarning: true,
global: { // thresholds for all files
statements: 94.09,
branches: 89.92,
functions: 92.67,
lines: 94.33
}
}
},
webpack: webpackConfig
});
}