Karma Code Coverage with Istanbul

July 24, 2015

Karma can generate code coverage using awesome Istanbul. If you want to generate the coverage, you need to configure up to three parts:

  • preprocessor coverage (required)
  • reporter coverage (required)
  • reporter options (optional)

Karma docs

Contents

Preprocessor

The preprocessor configures which files should be tested for coverage.

preprocessors = {
  'www/js/**/*.js': 'coverage'
};

Important

You should not however include the files that aren’t directly related to your program, e.g. libraries, mocks, neither tests.

Reporter

To activate the coverage reporter add this to your configuration file.

        reporters = ['coverage'];

This will create a coverage report for every browser that the tests are run in. In addition, it will create a JSON file that outputs the intermediate data.

Reporter Options

The reporter defaults to the following values.

coverageReporter = {
  type : 'html',
  dir : 'coverage/'
}

Other

To make it work I needed to change the karma.conf.js.

// the plugins I am pusing
plugins: [
      "karma-phantomjs-launcher",
      "karma-jasmine",
      "karma-coverage"
    ],

Obviously installing everything

$ npm install -g istanbul
$ npm install -g karma-coverage