Note: This blog post is inspired on Xavier Seignard’s blog post. He gives a longer introduction on it, and integrates it together with Sonar. You should check it out.
Code coverage is convenient to get an overview of how well-tested your program is. I’m going to show you how to set up code coverage using Mocha, Istanbul and LCOV in two easy steps.
Step 1: Install dependencies
First we’ll install LCOV, which
is a graphical frontend for the
gcov tool and can parse the output of code
info files. The gcov format is a universal format for code coverage
In OSX (using homebrew):
brew install lcov
In linux (Ubuntu):
apt-get install lcov
Declare the remaining dependencies in the
package.json of your project:
Step 2: Set up a Makefile
With everything installed, we just need to automate generation of
the coverage report. I am using a
Makefile to do that, but it could be a
simple script. After all, it is just executing bash commands.
Create a file named
Makefile in the root of our project folder and declare
some variables containing the location of executables and a filter for test
Next, we make a case for generating a coverage report:
In the preceding code, Istanbul instruments our source code in the
folder, so anything outside of
lib won’t be taken into account by the report.
The original folder is not modified, just renamed temporarily while the report
is generated. Next,
lib is restored to its original name and we get rid of
other folders generated in the process.
You should change
lib to the location of your source code.
As a nice final touch, we can add two extra actions to our Makefile,
With this, we now have available a
coverage action in the Makefile, and we can
execute the following in the root of our project folder:
and Istanbul will generate a complete report in the
report folder. You can
now go there and open
index.html to see your coverage by lines, functions and