Code Coverage in Node.js

Quick Intro

I needed a way to get code coverage for the Splunk JavaScript SDK

Nothing quite fit what I needed, so I wrote Cover

A bit of history

JSCoverage

Bunker

runforcover

Cover

How does it work?

Hooking into require


require.extensions['.js'] = function(module, filename) {
    
    // Check if file is ignored
    ...

    // Read from disk
    var data = stripBOM(fs.readFileSync(filename, 'utf8').trim());
    data = data.replace(/^\#\!.*/, '');
    
    // Instrument
    var instrumented = instrument(data);    
    var newCode = addInstrumentationHeader(template, filename, instrumented, pathToCoverageStore);
    
    ...
    
    // Return to Node.js
    return module._compile(newCode, filename);
};    
  

Parse, instrument and regenerate code

Statement transformation

Expression transformation

Block transformation

All together now

How instrumenting works

That's pretty much it

There's a bit more...

Some thoughts...

100% code coverage doesn't mean your code is 100% correct

The trouble is that high coverage numbers are too easy to reach with low quality testing.

Martin Fowler

Coverage can be useful for detecting areas where you need more testing

Block-level coverage is a much more useful metric to track

Next steps

Make it run in the browser

Get it ready for wider release

How you can help

Most importantly... try it out!

npm install cover -g

Questions!