karma-coverage is the standard plugin for adding Istanbul-based code coverage to a Karma project. This lesson walks through installing it, wiring it into preprocessors, and generating your first report.
Installing and Wiring Up karma-coverage
karma-coverage works as both a preprocessor (instrumenting matched source files) and a reporter (aggregating collected coverage data into a report). Both roles need to be configured for it to work end to end.
Step 1 (preprocessors) determines *which files* get instrumented.
Step 2 (reporters) activates the coverage reporter so it actually runs.
Step 3 (coverageReporter) configures *how* the aggregated data is output (formats, directory).
Missing any one of these three pieces results in either no instrumentation or no report at all.
karma-coverage Setup Cheat Sheet
The three required wiring points and common gotchas.
Piece
Purpose
Common Mistake
preprocessors
Instruments matched source files
Accidentally instrumenting spec files too
reporters: [..., 'coverage']
Activates the coverage reporter
Forgetting to add 'coverage' here
coverageReporter.dir
Output directory for reports
Not gitignoring the generated directory
coverageReporter.reporters
Output format(s) to generate
Only generating one format when CI needs another
Excluding Spec Files from Instrumentation
The glob pattern src/**/!(*.spec).js uses extended glob syntax to match every .js file under src/ except those ending in .spec.js. Getting this pattern right is the single most common source of confusing, inflated, or deflated coverage numbers.
Coverage reports are generated artifacts, regenerated on every test run — they don't belong in version control any more than build output does.
# .gitignore
coverage/
Common Mistakes
Instrumenting spec files alongside source files due to an overly broad glob pattern.
Adding a preprocessors entry for coverage but forgetting to add 'coverage' to reporters.
Committing the generated coverage/ directory to version control.
Configuring only one output format when both a human-readable (HTML) and CI-readable (lcov/cobertura) format are actually needed.
Key Takeaways
karma-coverage requires configuration in both preprocessors (instrumentation) and reporters (report generation).
Excluding spec files from instrumentation is essential for accurate coverage numbers.
coverageReporter.dir and coverageReporter.reporters control where and in what format reports are generated.
Generated coverage directories should be gitignored, not committed.
Pro Tip
After first wiring up karma-coverage, open the generated HTML report in a browser and click into a file you know well. Confirming the highlighted covered/uncovered lines match your actual expectations catches configuration mistakes far faster than staring at summary percentages alone.
You now know how to set up karma-coverage. Next, explore the different coverage reporter output formats available.