Using Istanbul With Mocha

Istanbul is extensively tested with mocha, which we use for many of our own repos.

At the end of the day, all you need to do is place the bin nyc in front of the existing test scripts in your package.json:

{
  "scripts": {
    "test": "nyc mocha --timeout=3000"
  }
}

that's it! this will instrument the code that your tests execute, and any subprocesses that it spawns.

#Using Alternative Reporters

By default nyc uses Istanbul's text reporter. Various other reporters are available. You can view the full list on the Using Alternative Reporters page.

If you'd like to specify alternate reporter, or would like to run multiple reporters, simply use the --reporter flag.

for instance, suppose you would like to output the default text report, along with an HTML coverage report.

{
  "scripts": {
    "test": "nyc --reporter=html --reporter=text mocha"
  }
}

This will output the text report to the terminal, as well as outputting the detailed html report to ./coverage/index.html.

#Integrating with Coveralls

coveralls.io is a great tool for adding coverage reporting to your continuous-integration flow. Here's how to get Istanbul integrated with coveralls and travis-ci.org:

  1. add the coveralls dependency to your module:
npm install coveralls --save-dev
  1. update the scripts in your package.json to include a bin for reporting coverage to coveralls:
{
  "script": {
     "test": "nyc --reporter=html --reporter=text mocha",
     "coverage": "nyc report --reporter=text-lcov | coveralls"
  }
}
  1. For private repos, add the environment variable COVERALLS_REPO_TOKEN to Travis.

  2. add the following to your .travis.yml:

after_success: npm run coverage

#What Now?

nyc and Istanbul provide many advanced configuration options a good place to start learning more is the istanbuljs/nyc README.

Quick Start

Adding coverage to your mocha tests could not be easier

$ npm install --save-dev nyc

Now, simply place the command nyc in front of your existing test command, for example:

{
  "scripts": {
    "test": "nyc mocha"
  }
}