I am trying to use Karma to run tests with accurate code coverage output for my files that use ES6+ including ES7 async/await syntax.
As a start, I managed to make it work when I have only one source file (i.e. no require
calls in my source files). I just told Karma to use babel
on it and configured babel-plugin-istanbul
on my .babelrc
.
karma.conf.js
:
preprocessors: {
"test/*.js": [ "browserify" ],
"lib/*.js": [ "babel" ]
}
Note that the "coverage"
preprocessor is not included on purpose, because that's what babel-plugin-istanbul instructs to do (and it works indeed). Also, I do need to browserify
the tests because there's a require('chai')
in there.
.babelrc
:
{
"presets": [ "env" ],
"env": {
"test": {
"plugins": [ "istanbul" ]
}
}
}
Great coverage results:
require()
: didn't workNow I want to make this work in my real situation, which is a lot of source files with require()
calls from one to the other. To make this work, instead of simply using the babel
preprocessor, I had to use the browserify
preprocessor, but now it seems to be ignoring my .babelrc
and not instrumenting the code with istanbul coverage stuff:
karma.conf.js
was changed to:
preprocessors: {
"test/*.js": [ "browserify" ],
"lib/*.js": [ "browserify" ]
}
Without this change, not even the tests would run. With it, the tests run, but the coverage does not work.
Wrong coverage results:
How can I fix this?
Since there's a lot going on, I decided to create a GitHub repo so that anyone can reproduce my situation instantly and easily:
To see the first part that works:
git clone https://github.com/papb/papb-stackoverflow-q-51812979.git
cd papb-stackoverflow-q-51812979
npm install
npm test
To see the part that doesn't work:
git checkout doesnt-work
npm test
To see the full diff from the two (just three lines): see the comparison on GitHub
OP here. I figured it out:
npm install browserify-istanbul
Add this to karma.conf.js
:
browserify: {
configure: function(bundle) {
bundle.transform(require('browserify-istanbul')({
ignore: ['test/*.js']
}));
}
}
Leave the preprocessors
as they were (no coverage
preprocessor!)
preprocessors: {
"test/*.js": [ "browserify" ],
"lib/*.js": [ "browserify" ]
}
That's it. You can get rid of the .babelrc
and the babel-plugin-istanbul
, they are not even necessary.