Here's a motivational sample of the output we'll be getting to:
Step 1: Installing JSCoverage and Mocha
If you're on a machine with Homebrew installed, getting this set up will be as easy as:
$ brew install jscoverageThere's also an apt package for you lucky linux folks:
$ sudo apt-get install jscoverageIf you don't have either of these, you'll be building it yourself. Which is really easy too:
wget http://siliconforks.com/jscoverage/download/jscoverage-0.5.tar.bz2 tar xvfj jscoverage-0.5.tar.bz2 cd jscoverage-0.5 ./configure make make installIt will be installed into /usr/local and you should be all set. Give
jscoveragea shot and you should see its default output.
There is an npm package by the creator of mocha, but I haven't given it a go yet.
You'll need a global version of mocha installed for the Makefile at the end, and for that you can roll with:
$ npm install -g mocha
Step 2: Loading JSCoverage in TestsNow that we have jscoverage installed, we need to call into it from our tests. Because of the way JSCoverage has to work, we first generate a folder equivalent to our
libfolder but jscoverag'ed:
$ jscoverage lib lib-covOn newer version of jscoverage, the library also can do highlight - but since that will mess up the test output, we'll want to turn it off. To run jscoverage without highlighting we go instead for:
jscoverage --no-highlight lib lib-covOnce we have this, our tests are still loading the copy in
lib. We need to go into each of our tests files, and if a certain environment variable is present, use
lib-covinstead. I like to do this by defining a variable at the top of my test and then basing other loads off of that:
var libpath = process.env['YOUR_LIBRARY_NAME_COV'] ? '../lib-cov' : '../lib'; var something = require(libpath + '/something'); var other = require(libpath + '/other');
The name of the environment variable should be something unique. The reason for a unique name is that if you using something like "COV" as the environment variable name, you'll end up also loading jscoverage'ed versions of other libraries you have as dependencies, and they'll cloud up your coverage reports.
Now we can run the tests with:
$ YOUR_LIBRARY_NAME_COV=1 mocha -R html-cov > coverage.html
And the coverage.html file will contain our coverage report
Step 3: Using a MakefileAll of this typing will get annoying pretty fast, and for that I use a Makefile. Here's what it should look like:
test: npm test coverage: jscoverage --no-highlight lib lib-cov YOUR_LIBRARY_NAME_COV=1 mocha -R html-cov > coverage.html rm -rf lib-cov .PHONY: test
With this in place, running
make test will run your tests, and running
make coverage will generate your coverage report!
A Few NotesI'd advise adding
.gitignorefile, so that they don't get versioned.
Also - "html-cov" will not show you test failures, so make sure you run
make test before pushing out new versions of anything.
ExampleFor an example of all of this in action, check out seejohnrun/htmlcov-example on GitHub!