Coverage testing in Node.js with Istanbul

What is Coverage Testing?

Coverage testing determines what proportion of your source code is covered by your tests. 

It's useful to be able to check this as your developing/writing tests/testing so that you can aim as close as possible for 100%

How do I use Coverage Testing in my Node.js / JavaScript application?

It is really easy to run coverage tests in your project, even easier if you are using a testing framework and have everything set up. 

There is a Node module called Istanbul, which takes care of everything for you. 
Read more about Istanbul here: https://github.com/gotwarlost/istanbul

1. Install Istanbul both globally and then add to your dev dependencies
npm install istanbul --save-dev
npm install istanbul --global

2. Run a quick coverage test on one of your test files like so
istanbul cover test/my-test.js

3. Add a script tag to your package.json to run a coverage command on ALL test's at once, easily 
"scripts": {
    "start": "node app.js",
    "test": "mocha",
    "cover": "istanbul cover node_modules/mocha/bin/_mocha --dir ./reports/coverage"
  }

(this works great for Mocha setup, and on Windows, may be slightly different for other testing frameworks)

4. Run your coverage tests!
npm run cover

You should see a nice summary of your coverage in the console. 
Also check out the more detailed HTML report that Istanbul kindly created for you. 
Don't forget to add the reports directory to your .gitignore !





Check out the example project on GitHub:

1 comment :

Post a Comment