Mahesh
Mahesh

Reputation: 863

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

Upvotes: 28

Views: 43628

Answers (3)

Raydot
Raydot

Reputation: 1586

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 add the following to package.json:

"test:coverage": "react-scripts test --env=jsdom --watchAll=false --coverage"

Then you can run:

npm run test:coverage

See either the answer I link to above or Watchmaker's answer even further above for more details.

Upvotes: 10

Watchmaker
Watchmaker

Reputation: 5308

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!

Upvotes: 40

Anupam Jagatdeo
Anupam Jagatdeo

Reputation: 151

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

Upvotes: 10

Related Questions