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 coverage info files. The gcov format is a universal format for code coverage stats.
In OSX (using homebrew):
1 | brew install lcov |
In linux (Ubuntu):
1 | apt-get install lcov |
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 files:
1 |
|
Next, we make a case for generating a coverage report:
1 | coverage: |
In the preceding code, Istanbul instruments our source code in the lib 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, clean and test:
1 | clean: |
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:
1 | make coverage |
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 files.
Happy testing!