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):
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 files:
# test files must end with ".test.js"
TESTS=$(shell find test/ -name "*.test.js")
Next, we make a case for generating a coverage report:
# check if reports folder exists, if not create it
@test -d reports || mkdir reports
$(ISTANBUL) instrument –output lib-cov lib
# move original lib code and replace it by the instrumented one
mv lib lib-orig && mv lib-cov lib
# tell istanbul to only generate the lcov file
ISTANBUL_REPORTERS=lcovonly $(MOCHA) -R mocha-istanbul $(TESTS)
# place the lcov report in the report folder,
# remove instrumented code and put back lib at its place
mv lcov.info reports/
rm -rf lib
mv lib-orig lib
genhtml reports/lcov.info –output-directory reports/
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,
rm -rf reports
$(MOCHA) -R spec $(TESTS)
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 files.