Mario Petrovic
Mario Petrovic

Reputation: 8332

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?

Upvotes: 52

Views: 88345

Answers (4)

giovannipds
giovannipds

Reputation: 3459

I believe that in your scenario it will be:

npm test my-component.test --collectCoverageFrom="my-component.tsx" --coverage 

The property you're looking for is --collectCoverageFrom, but this property is a little tricky.

  • It can accept a relative path as string, e.g. --collectCoverageFrom="src/your-path/my-component.tsx" ✅;
  • But it cannot accept a path not as a string, e.g. --collectCoverageFrom=src/your-path/my-component.tsx ❌;
  • It can accept arrays, e.g. --collectCoverageFrom="['src/your-path/my-component.tsx', 'src/one-more-path/']" ✅;
  • But it will not accept arrays formatted unwell, e.g. --collectCoverageFrom="[src/your-path/my-component.tsx, src/one-more-path/]" ❌;

Sometimes it will be easier to just use some **/* to identify if it will get what you want, e.g:

npm test my-component.test --collectCoverageFrom="my-path/**/*" --coverage 

Just remember that:

  • (1) the first option is the test file;
    • my-component.test.jsx;
  • (2 the second option is what you're intending to check coverage:
    • my-component.jsx;
npm test (1) --collectCoverageFrom="(2)" --coverage 

Hope to have helped somehow. 😊

Upvotes: 0

Soham Bhattacharjee
Soham Bhattacharjee

Reputation: 1

You can try this out, it works for me

npm run coverage -- <filename>.test.ts

Upvotes: -2

Ali Raza Arain
Ali Raza Arain

Reputation: 17

npm run test:coverage -- fileName.component.spec.ts

Upvotes: -5

Mario Petrovic
Mario Petrovic

Reputation: 8332

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.

Upvotes: 85

Related Questions