Javascript coverage with Gulp, Karma & Istanbul

Creating modular, testable code in your Javascript projects is imperative. Coverage enables developers to measure their unit tests. Istanbul is one such tool and plays nicely with gulp. It can be used to cover statements, branches and functions.

What coverage tools are:

Useful indicators for project health, when combined with CI pipelines they ensure new and modified code is suitably covered and less likely to introduce bugs.

What coverage tools are not:

A guarantee that your tests are well written. You can have 100% code coverage, but if the tests are brittle, then it's for nothing.

Istanbul Coverage example

I've put together an example project to demonstrate how to integrate coverage into a project.

git clone

You'll need to globally install gulp on your machine in order to run gulp on the CLI:

cd example-istanbul-gulp-coverage
npm install 
npm install gulp -g

The example project implements YACA (Yet Another Calculator App) a crude calculator, with addition and subtraction files located in calculator/js. The project also contains a gulpfile.js and karma.conf.js, we'll walk through this later. For now we just want to run the default gulp task:


You should see coverage/js/index.html open in your browser with the score of both files, add.js at 100% and subtract.js at 71%.

istanbul coverage

Clicking into a filename shows line by line details about what code is being covered. I've deliberately left off some tests on subtract.test.js so you can compare the results.

Coverage command explained:

When we executed the gulp command the following events sequence is triggered:

  1. The unit:coverage gulp task is executed, which starts a karma test runner and sets up the configuration options
  2. The phantom browser runs and the tests are executed inside of it.
  3. The output is reported back to the gulpfile, Istanbul then creates a new /coverage directory to store the results.
  4. A new browser tab is automatically opened displaying the Istanbul report.

You can extend this example project to implement AMD, or switch mocha for jasmine, as per your requirements.

Further reading

Coverage testing can be valuable component of a wider CI toolchain. If your interested check out some of these valuable resources.