A coverage tool is something that I’ve always wanted for my Node.js development. I certainly don’t depend on one, but I like when a coverage tool can point out things I’ve obviously missed tests for.

Tools like this are tough in Javascript, because our tracing ability is limited. Yesterday, though two new test runners were added for mocha, my favorite JS testing framework. They are js-cov and html-cov. They work really well, and you should definitely give them a look.

Wanting to know how they worked, I dug a bit deeper, and quickly found that they depend on output for jscoverage to work. What jscoverage does, is create an instrumented copy of your code, by breaking it up and inserting lines to track counters of what was touched during execution, and how many times. Imagine we had this simple code (file:example.js):

for (var i = 0; i < 10; i++) {
  console.log('hello world');

Running jscoverage lib lib-coverage will produce something like:

// ...
for (var i = 0; (i < 10); (i++)) {
  console.log("hello world");

So this is code that still works, but when run, will record which lines were touched. Then the mocha runner just runs the tests, parses the output and puts it in a pretty format. Really cool, useful stuff!

Pro tip: jscoverage also highlights code by default and I found that it was messing up mocha’s output. You can turn it off with jscoverage --no-highlight.