46

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?

2 Answers 2

75

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.

8
  • 2
    If someone wants to add multiple files, you can use this: --collectCoverageFrom='["packages/**/index.js"]' --coverage . Original Ref: github.com/facebook/jest/issues/1932 Oct 26, 2021 at 10:38
  • Tried using the command from the above comment, but wouldn't work through the CLI. According to the docs, looks like it no longer takes an array, just the glob. collectCoverageFrom="packages/**/index.js" --coverage worked for me
    – Josh
    Oct 17, 2022 at 21:49
  • 1
    If you add path/spec_file after the --collectCoverageFrom..., only that file will have the tests run. For example, npm test my-component.test -- --coverage --collectCoverageFrom=src/components/my-component/my-component.tsx src/components/my-component/my-component.spec.tsx.
    – tim.rohrer
    Oct 22, 2022 at 18:34
  • That is correct. You can run also all tests and take only specific coverage info. Oct 22, 2022 at 19:16
  • 2
    This worked for me: npm test -- [fileName] --coverage
    – Sanchitos
    Aug 17, 2023 at 18:52
-4
npm run test:coverage -- fileName.component.spec.ts
1
  • 1
    Your answer could be improved with additional supporting information. Please "edit" to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer
    – nima
    Oct 25, 2022 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.