Test Coverage With Mocha and Istanbul


###Update (spoiler)###


When using the method of nesting tests as described here, the final syntax becomes a little different. (Note that I’ve also set the environment variable).

1
NODE_ENV="test" istanbul cover -x='public/**' --include-all-sources _mocha $(find test/tests -name '*.js')



Istanbul is a tool you can use for testing coverage analysis. It has a guide here:
https://github.com/gotwarlost/istanbul

I was introduced to it here:
http://stackoverflow.com/questions/16633246/code-coverage-with-mocha

Install globally…

1
$ npm install -g istanbul

The key command (for me anyway) is:

1
$ istanbul cover _mocha

The _mocha is what the mocha command uses at a deeper level. The code needs to be run with this executable. See their GH for more info.

A coverage directory is created by Istanbul. This directory contains the results of your tests including a nicely formatted HTML report.

To open that up we can type:

1
$ open coverage/lcov-report/index.html

Here’s a sample view of what pulls up in my browser:

Istanbul "All" report

I could probably ignore the config directory :| We can do that with a modified command:

1
$ istanbul cover -x "config/*" _mocha

You can click any of the folders to drill down and see all the files.

Note: Only files that are pulled into the test suite are examined and included in the results. If you leave files completely untested, your results will not be accurate.

You can ultimately drill down into each file too. Here’s a view:

Istanbul "detail" report

We can see what never occurs in my tests. We see a couple code branches that never get tested. We also see that an entire function is not tested.

Pretty cool.

avatar

Dev Blog