Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get code coverage in react with react testing library

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?

enter image description here

like image 229
Mahesh Avatar asked Sep 11 '19 09:09

Mahesh


3 Answers

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!

like image 138
Watchmaker Avatar answered Nov 20 '22 06:11

Watchmaker


Since react-scripts has incorporated jest configuration, you can just type in npm run test --coverage or yarn test --coverage, to generate coverage report.

like image 8
Anupam Jagatdeo Avatar answered Nov 20 '22 06:11

Anupam Jagatdeo


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

like image 2
Dave Kanter Avatar answered Nov 20 '22 06:11

Dave Kanter