Measuring React App Test Coverage with Puppeteer and Istanbul

I’m working on a React project built with create-react-app. I’ve got some UI tests using Jest and Istanbul, but I’m struggling to get accurate code coverage for these tests.

I want to keep using Jest since it’s already set up for my unit tests. I’d rather not eject from create-react-app unless it’s absolutely necessary.

Here’s what I’ve tried so far:

In my package.json, I added this script:

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

When I run npm run ui-coverage -- --coverage, it only seems to capture the test files, not the actual app code.

I’ve looked into other solutions like puppeteer-to-istanbul, but it doesn’t support source maps. I’ve also checked some books and online resources, but haven’t found a clear solution.

Has anyone successfully set up code coverage for UI tests in a create-react-app project without ejecting? Any tips or tricks would be really helpful!

I’ve encountered this challenge before. One approach that worked well for me was using the @cypress/code-coverage plugin. It’s designed to work with Create React App projects and doesn’t require ejecting.

First, install the necessary dependencies:

npm install --save-dev @cypress/code-coverage

Then, update your cypress/support/e2e.js file to include:

import '@cypress/code-coverage/support'

Next, modify your cypress.config.js:

module.exports = {
  // ... other config
  setupNodeEvents(on, config) {
    require('@cypress/code-coverage/task')(on, config)
    return config
  },
}

This setup should give you accurate coverage reports for your UI tests without compromising your existing Jest setup. It’s been reliable in my experience and might be worth exploring for your project.

hey mia92, i’ve faced similar issues. hav u tried using jest-puppeteer? it integrates well with cra and can handle coverage. just install it, update ur jest config, and modify ur test script. might need to tweak some settings, but it worked for me without ejecting. good luck!

I’ve been down this road before, and it can be tricky. Have you considered using Istanbul’s nyc command-line client? It’s a powerful tool that can work alongside Jest without ejecting from create-react-app.

Here’s what worked for me:

  1. Install nyc: npm install --save-dev nyc
  2. Update your package.json script:
"ui-coverage": "nyc --reporter=lcov --reporter=text-summary npm run test -- --env=jsdom --testMatch='**/*.ui-test.{js}'"

This approach leverages your existing Jest setup while providing more accurate coverage reports. It might take some tweaking to get it just right, but it’s been solid for my projects.

One caveat: make sure your .gitignore includes the .nyc_output directory to keep things clean. Hope this helps!