Question

How to run Jest tests with coverage for one file

I want to have coverage report for only one file that I am working on at the moment.

It is a bit overwhelming to have the full table of coverage for the whole application files and then search for the one I need.

What I tried was to run test for one file and add --coverage. But it shows coverage for all files:

package.json

...
"test": "react-scripts test",
...

My command

npm test my-component.test --coverage

Is there an option that I can add to this command to show me only my-component.tsx coverage?

 48  77553  48
1 Jan 1970

Solution

 80

The solution is to add one small option --collectCoverageFrom to collect only for a certain file (i.e. component). This is based on this post

NPM version
npm test my-component.test -- --coverage --collectCoverageFrom=src/components/my-component/my-component.tsx
Notice an extra -- before --coverage.... This needs to be passed for npm as following options provided will not be taken into consideration without it.

YARN version
yarn test my-component.test --coverage --collectCoverageFrom=src/components/my-component/my-component.tsx

This will show coverage table only for my-component.tsx.

NOTE:

The path to my-component.tsx file needs to be relative to project root and exact. It cannot be relative as I did for my-component.test.

2021-03-05

Solution

 -1

You can try this out, it works for me

npm run coverage -- <filename>.test.ts
2024-04-19