'How do I instrument React and Cypress for code coverage?

I want to display code coverage for testing React in Cypress The package.joson look like this

{
  "name": "guitesttraining",
  "version": "0.1.0",
  "private": true,
  "jest": {
    "collectCoverageFrom": [
      "src/components/**/*.js"
    ],
    "coverageReporters": [
      "cobertura",
      "text"
    ]
  },
  "dependencies": {
    "@testing-library/react": "^12.1.4",
    "@testing-library/user-event": "^13.5.0",
    "jest-junit": "^13.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "serverless-finch": "^4.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts -r @cypress/instrument-cra start",
    "build": "react-scripts build",
    "test": "react-scripts test --coverage --reporters=default --reporters=jest-junit",
    "eject": "react-scripts eject",
    "cypress:run": "cypress run --record --key 3339aabe-1bcc-4f8c-8098-d08f47ac0b9b",
    "postcypress:run": "npx nyc report --reporter=cobertura",
    "cypress:open": "cypress open"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@cypress/code-coverage": "^3.9.12",
    "@cypress/instrument-cra": "^1.4.0",
    "@testing-library/cypress": "^8.0.2",
    "@testing-library/jest-dom": "^5.16.2",
    "cypress": "^9.5.2",
    "cypress-jest-adapter": "^0.1.1",
    "nyc": "^15.1.0"
  }
}

The cypress/support/index.js

import './commands'
import 'cypress-jest-adapter'
import '@testing-library/cypress/add-commands'
import '@cypress/code-coverage/support'

The cypress/pluging/index.js

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

After I have executed run start "react-scripts -r @cypress/instrument-cra start"

Console do not contain window.coverage object in the "Application under test iframe" When I run npm run cypress:run I get a error message

  - should toggel display and hide of details ⚠️ file /Users/steinko/development/cypresstaining/webtestingtraining/.nyc_output/out.json
has no coverage information Did you forget to instrument your web
application? Read
https://github.com/cypress-io/code-coverage#instrument-your-application

What must I do to instrument the web application? I toght that running react-scripts -r @cypress/instrument-cra start instrumeneted the web application



Solution 1:[1]

I found a issue, instrument-cra still does not support react-scripts v5. After I try react-scripts v4.0.3, it does not work also.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iPiranhaa