How do I exclude files from karma code coverage report?

Le Garden Fox picture Le Garden Fox · Mar 19, 2015 · Viewed 29.5k times · Source

Is there a way to exclude files from code coverage report for the karma coverage runner https://github.com/karma-runner/karma-coverage ?

Answer

MarcoL picture MarcoL · Mar 21, 2015

You can use several techniques here: karma uses minimatch globs for file paths and use can take advantage of that to exclude some paths.

As first solution I'd say try to add only the paths of the file to preprocess with the coverage:

// karma.conf.js
module.exports = function(config) {
  config.set({
    files: [
      'src/**/*.js',
      'test/**/*.js'
    ],

    // coverage reporter generates the coverage
    reporters: ['progress', 'coverage'],

    preprocessors: {
      // source files, that you wanna generate coverage for
      // do not include tests or libraries
      // (these files will be instrumented by Istanbul)
      'src/**/*.js': ['coverage']
    },

    // optionally, configure the reporter
    coverageReporter: {
      type : 'html',
      dir : 'coverage/'
    }
  });
};

The one above is the default example in karma-coverage and it shows that only those files in the src folder will be preprocessed.

Another trick can be to use the ! operator to exclude specific paths:

preprocessors: {
  // source files, that you wanna generate coverage for
  // do not include tests or libraries
  'src/**/!(*spec|*mock).js': ['coverage']
},

The one above makes the coverage run only on those Javascript files that do not end with spec.js or mock.js. The same can be done for folders:

preprocessors: {
  // source files, that you wanna generate coverage for
  // do not include tests or libraries
  'src/**/!(spec|mock)/*.js': ['coverage']
},

Do not process any Javascript files in the spec or mock folder.