How to generate a code coverage report using Jest

You have several options, based on how often you want to look at the output.

Setup 1: One-off Check

If it’s a punctual check, just leverage the --coverage flag:

./node_modules/.bin/jest --coverage

N.B. You’ll note I use my local path to Jest as I usually avoid using global modules. My main motivation is to ensure version consistency.

And you can pick a specific type of output. My favorite is probably the html one: it will create a coverage directory with an index.html file that you can open with any browser. Then navigate between pages, you should find that output useful to understand what exactly got tested:

./node_modules/.bin/jest --coverage --coverageReporters=html

Setup 2: Recurring Script

On the other hand, if you’re planning to generate such a report systematically, you can rely on your Jest config JSON file to do so. Just add:

{
    "collectCoverage": true,
    "coverageReporters": ["html"]
}

N.B. You could totally rely on flags, exclusively, and define a command in your package.json to make sure they’re all used whenever you call npm run test. That being said, I like gathering all my Jest preferences within my JSON file.