npm test -- --coverage never exits

Coverage won't work with Jest in watch mode.

Because "react-scripts test --env=jsdom" works in watch mode by default, the watch mode has to be switched off while generating the coverage output.

The following excerpt from the package.json contains a line "coverage" for illustration, how code coverage can be achieved within an app which was bootet by create-react-app.

It's just the modified "test" script, where the options --watchAll=false and --coverage are added in combination:

 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "coverage": "react-scripts test --env=jsdom --watchAll=false --coverage",
    "eject": "react-scripts eject"
  }

Please note that it is obsolete to use standalone double-dash -- .


-- --coverage part won't work, and should use one of the commands below to set CI to true.

By default npm test runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called CI.

source: React docs

Windows (cmd.exe)

  • set CI=true && npm test

  • set CI=true && npm run build

Windows (Powershell)

  • ($env:CI = "true") -and (npm test)

  • ($env:CI = "true") -and (npm run build)

Linux, macOS (Bash)

  • CI=true npm test

  • CI=true npm run build


NOT included in the docs

For Docker (node and react):

docker run -e CI=true [myImage] npm run test


Most of the time this issue can be occur because of following reasons.

  1. Not mentioning the required npm-script arguments in the package.json file. If you use create-react-app to create your react application, then it will not accept any command line arguments. To resolve this problem, add following line under the script tag in your package.json.

    "test": "react-scripts test --coverage --watchAll", //mark --watchAll=false if you want.
    
  2. Not mentioning the required jest configuration arguments in the package.json or jest.config.js files. You should mention the files which needed to include in your test coverage under the jest configurations. Add following configurations in your package.json.

package.json

  "jest": {
    "collectCoverageFrom": [
      "src/**/*.js",
      "!src/index.js", // files you need to avoid in test coverage
      "!src/hooks/*.js",
      "!src/context/*.js"
    ],
    "coverageThreshold": {
      "global": {
        "branches": 90,
        "functions": 90,
        "lines": 90,
        "statements": 90
      }
    },
    "coverageReporters": [
      "html",
      "text"
    ]
  },