Search code examples
reactjstypescriptjestjsistanbul

Jest finds tests but doesn't collect coverage


I trying to collect test coverage for this project using

yarn test --coverage # i.e. "react-scripts test --coverage"

My jest config is this:

  "jest": {
    "collectCoverageFrom": [
      "src/**/*.ts*"
    ],
    "coverageThreshold": {
      "global": {
        "lines": 90,
        "statements": 90
      }
    }
  }

and my folder structure is as follows:

.
├── package.json
├── postcss.config.js
├── public/
├── README.md
├── src/
│   ├── App.css
│   ├── App.test.tsx
│   ├── App.tsx
│   ├── assets/
│   ├── components/
│   │   ├── Emoji/
│   │   │   ├── Emoji.test.tsx
│   │   │   ├── Emoji.tsx
│   │   │   └── index.ts
│   │   └── Home/
│   │       ├── Home.css
│   │       ├── Home.test.tsx
│   │       ├── Home.tsx
│   │       └── index.ts
│   ├── index.css
│   ├── index.tsx
│   ├── react-app-env.d.ts
│   └── serviceWorker.ts
├── tsconfig.json
├── yarn-error.log
└── yarn.lock

Jest is being able to find all the tests but it fails to collect coverage:

 PASS  src/components/Home/Home.test.tsx
 PASS  src/components/Emoji/Emoji.test.tsx
 PASS  src/App.test.tsx
----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |        0 |        0 |        0 |        0 |                   |
----------|----------|----------|----------|----------|-------------------|

Test Suites: 3 passed, 3 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        3.432s
Ran all test suites.

What am I missing? What should I add to the configuration to get the coverage?

Any hint is welcome :)

Tries

  1. Changing the glob pattern to "src/**/*.{js,jsx,ts,tsx}".
  2. Removing node_modules and then running yarn to reinstall everything.
  3. Removing node_modules and yarn.lock, and then reinstall everything, which led to another bug, which I tried to solve installing that particular dependency, but it didn't work.
  4. Cloning the repository from GitHub and then running the command on the fresh version.
  5. Switching to a different Node version (v10.16.2, and v11.7.0).

Solution

  • The quick fix I said in my comment, using --watchAll instead, eg: react-scripts test --coverage --watchAll.

    Just for future reference, I think ideally we should be using --watch, which would only run on changed files, but it gave me the same trouble. I think it's related to this issue '--coverage --watch' should calculate coverage for all files at first iteration and also this issue No coverage when running in watch mode. I'm not sure why it worked for some people and not you, presumably something to do with Git and staging of files.