reactjstypescriptjestjsreact-scripts

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?


Solution

  • 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.