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?
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.
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.
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.
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.
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 versionnpm 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 versionyarn 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With