Today I learned

Getting Mocha coverage reports using Istanbul

This is all you really need to run coverage reports on Mocha tests via Istanbul.

istanbul cover _mocha

Opening reports

Your reports will be available under coverage/. By default, you'll get JSON files and an HTML report.

open coverage/lcov-report/*.html

Improving your setup

Locking istanbul

Preferably, though, you'll want to add istanbul to your project so you can pin down the version you need and have it available on your CI.

npm install --save-dev istanbul
./node_modules/.bin/istanbul cover _mocha

Adding to gitignore

There's no need to commit the coverage reports.

echo "/coverage" >> .gitignore

Making an npm task

To make things a bit easier, add a script to your package.json to run this. After that, just invoke npm run coverage.

package.json
{
  ...
  "scripts": {
    "coverage": "istanbul cover _mocha -- -R spec"
  }
}

Travis integration

If you're using Travis to automate your tests, you can also set it up to show coverage reports on your builds. Looks like this.

travis.yml
script: npm run coverage

You have just read Getting Mocha coverage reports using Istanbul, written on July 06, 2015. This is Today I Learned, a collection of random tidbits I've learned through my day-to-day web development work. I'm Rico Sta. Cruz, @rstacruz on GitHub (and Twitter!).

← More articles