Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Jest coverage for one component 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?

like image 786
Mario Petrovic Avatar asked Mar 05 '21 12:03

Mario Petrovic


People also ask

How do you test a single file with jest?

In order to run a specific test, you'll need to use the jest command. npm test will not work. To access jest directly on the command line, install it via npm i -g jest-cli or yarn global add jest-cli . Then simply run your specific test with jest bar.

How does jest collect coverage?

Jest is collecting coverage only on the function under tests, not from the entire project. This means that despite we are seeing 100% coverage here, potentially we are testing only a fraction of our code. Now Jest is identify correctly what needs to be tested.

Does jest have code coverage?

As part of the output Jest generates, you'll see not only the test results but also the code coverage report. Since the current code is very simple, you should be getting 100 percent code coverage.

How do I run code coverage?

To calculate the code coverage percentage, simply use the following formula: Code Coverage Percentage = (Number of lines of code executed by a testing algorithm/Total number of lines of code in a system component) * 100.


Video Answer


1 Answers

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.

like image 157
Mario Petrovic Avatar answered Oct 12 '22 07:10

Mario Petrovic