Measuring React App Test Coverage with Puppeteer and Istanbul

Hey everyone, I’m working on a React app built with create-react-app and I’m trying to figure out how to get code coverage for my UI tests. I’m using Jest and Istanbul for unit tests, and I’d like to keep using Jest for consistency.

I’ve tried a few things already:

"scripts": {
  "uitest": "react-scripts test --env=jsdom --verbose --testMatch='**/*.ui-test.{js}'",
}

When I run npm run uitest -- --coverage, it only seems to capture the tests, not the actual app code.

I’ve looked into ejecting from create-react-app, but I’d rather avoid that if possible. I’ve also checked out puppeteer-to-istanbul, but it doesn’t support source maps.

Has anyone successfully set up code coverage for UI tests in a similar setup? Any tips or tricks would be super helpful. Thanks!

I’ve been down this road before, and it can be tricky. One approach that worked for me was using react-app-rewired along with babel-plugin-istanbul. This combo lets you instrument your code without ejecting from CRA.

Here’s what I did:

  1. Install the necessary packages
  2. Create a config-overrides.js file in your project root
  3. Modify your package.json scripts

The key is to ensure your app code gets instrumented before the tests run. Then, when you execute your Puppeteer tests, the coverage data should be collected.

It takes some setup, but once it’s working, you’ll get the coverage reports you’re after. Just remember to exclude test files and any irrelevant code from the coverage calculations to get meaningful results.

I’ve encountered this issue before, and found a solution using nyc (the command-line interface for Istanbul) in combination with Puppeteer. Here’s what worked for me:

  1. Install nyc as a dev dependency.
  2. Wrap your app’s start command with nyc.
  3. Run Puppeteer tests against this instrumented version.
  4. Use nyc report to generate coverage.

This approach doesn’t require ejecting from CRA or major config changes. It does need some script tweaks and careful setup, but it provides accurate coverage for UI tests.

Remember to configure nyc to include only relevant source files and exclude test files. Also, ensure your Puppeteer tests are comprehensive to get meaningful coverage data.

This method has its quirks, but it’s been reliable for my React projects.

hey mike, i’ve had similar issues. have u tried using cypress for e2e testing? it has built-in code coverage support and works well with react apps. no need to eject from CRA. might be worth checking out if jest isn’t cutting it for UI tests. good luck!