I have written unit tests using react testing library(@testing-library/react & @testing-library/dom) and jest-dom(@testing-library/jest-dom). I am able to run my tests successfully.
I am not using jest/jest-cli complete pacakge. I am using react testing library along with that jest-dom(@testing-library/jest-dom) it might be some sub pacakge or something i am not sure what to call it exactly.
How to get code coverage using react testing library?
Well, create-react-app is giving you a lot out of the box but it is also imposing some constraints...
You can't just add the flag --coverage
to npm run test
because that script is already running your tests in watch mode (and things like running only failed tests and other things that you can do in the interactive mode would affect your coverage report anyway).
So first thing first, run your test in single run mode.
CI=true react-scripts test --env=jsdom
And because you already have a test task in your package.json you can simplify your task as so:
CI=true npm test -- --env=jsdom
Alright, we are getting closer...
So now, on top of that add the --coverage
flag and you are all set:
CI=true npm test -- --env=jsdom --coverage
To summarize your npm task could be like:
"test:coverage": "CI=true npm test -- --env=jsdom --coverage"
And you will see your report in the terminal and the coverage
folder will be generated, where you can see a lot of useful info, by the way!
Since react-scripts
has incorporated jest
configuration, you can just type in
npm run test --coverage
or yarn test --coverage
, to generate coverage report.
An actual answer to this question exists: npm test -- --coverage never exits
The RTL doesn't provide testing coverage stats, but Jest does if you run:
npm run test:coverage
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