JavaScript test coverage with blanket.js

15 Jul 2013

Blanket.js is a test-coverage tool for JavaScript / Node. It's about 9 months old now, but I'm still amazed how easy it is to "configure" for a typical Node project.

While some tools require additional build steps (like instrumening your code into a separate folder), Blanket integrates with Node's require() to instrument JS code on the fly. This works for server-side Node.js code, as well as client-side code that uses the require syntax (browserify).

The simplest setup with Mocha is:

npm install blanket --save-dev
mocha -r blanket -R html-cov > coverage.html

Which generates an HTML report like:

HTML report

Basic configuration can be done through the package.json, for example specifying the source location or which folders to ignore.

"scripts": {
    "blanket": {
        "pattern": "src",
        "data-cover-never": "node_modules"

Coffee-script and other config tricks

Getting Blanket to work with coffee-script is relatively easy. In my case, the coffee-script options were specified in mocha.opts, so all I needed was "activating" blanket's handler for require(''). This might have changed since, but for now it's an extra configuration in the package.json:

"blanket:" {
    "loader": "./node-loaders/coffee-script"

It then picks up all coffee tests, and shows the compiled JavaScript version in the reports.

Another thing I noticed is how blanket only seems to instrument files that are required by a unit test. A simple fix to cover the whole codebase was to force every file to be required before running the tests, using mocha's before function, and the require-dir module.

before ->
    matchesBlanket = (path) -> path.match /node_modules\/blanket/
    runningTestCoverage = Object.keys(require.cache).filter(matchesBlanket).length > 0
    if runningTestCoverage
        require('require-dir')("#{__dirname}/../src", {recurse: true, duplicates: true})

Finally, with all of this working, you might want to integrate it with your build pipeline / dashboard. Mocha provides a different reporter that does just that:

mocha -r blanket -R json-cov > coverage.json

This generates the report in JSON format, where content['coverage'] and content['sloc'] can be a good start. My current project displays them on our dashing dashboard. While we don't strive for 100%, it's conforting to see a reasonable & pragmatic number on there!

Coverage dashboard