59

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).
Lual
  • 2,848
  • 1
  • 20
  • 27
  • 2
    I downloaded your project and ran the test. It collected coverage correctly – Tien Duong Aug 11 '19 at 15:15
  • @TienDuong O.O, then it must be something related to my environment, what's your OS and Node version? did you run the tests using yarn or npm? – Lual Aug 11 '19 at 16:31
  • 1
    I used Win 10, Node 10.16 and yarn – Tien Duong Aug 11 '19 at 16:38
  • @TienDuong thanks for the info, I downgraded my Node version and rerun and still no luck. I'm using Linux though, but I'm also able to collect coverage in a work project that has almost the exact config in this machine, so it's kinda weird :/ – Lual Aug 11 '19 at 16:48
  • 3
    I had similar trouble, not sure if for similar reasons. I added "--watchAll", so `react-scripts test --coverage --watchAll` and it worked... – atomictom Nov 05 '19 at 00:24
  • @atomictom it worked! thanks! please post the comment as an answer to accept it as the solution :) – Lual Nov 08 '19 at 11:46
  • adding --watchAll or --watchAll:false does not work for me – Jason G Feb 03 '20 at 19:16
  • the glob patterns in `collectCoverageFrom` and `coveragePathIgnorePatterns` are often cause for trouble. It's a good idea to comment them out and see if it works then. – til Jul 28 '23 at 07:01

17 Answers17

79

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.

atomictom
  • 1,637
  • 16
  • 14
  • yes, my problem('Failed to collect coverage from untested files') has been fixed just by using: --coverage --watchAll – SeyyedKhandon Jan 25 '20 at 10:45
  • Wow the linked `--coverage --watch` issue explains a lot. Why would they only collect coverage from changed files in git by default?! – TemporaryFix Dec 30 '22 at 01:46
26

Not necessarily the solution in the original questioner's case, but i ran into the exact same problem and this was my solution:

I found that when upgrading jest (from 23 to 26) that i had this issue, and the resolution was to run with the --no-cache option. Presumably they changed something about these coverage reports internally such that the cached data was incompatible.

Jemar Jones
  • 1,491
  • 2
  • 21
  • 27
  • 3
    I have upgraded from 24 to 26 and running with `--no-cache` once solved the issue. After that I had to use `--watchAll` for the coverage task, otherwise it was showing empty results – Anton Matosov Nov 04 '20 at 19:44
  • @AntonMatosov could u please check https://stackoverflow.com/questions/64727591/jest-coverage-in-a-node-typescript-project-always-returns-empty/64745848#64745848, I am still facing the same issue – muthu Nov 09 '20 at 05:36
  • In my case, the jest coverage is updating, but the Istanbul coverage html file is not. – darKnight Apr 15 '21 at 16:35
14

Seems to be working fine on Linux Mint 19.2. I'd suggest changing your jest config to something a bit more flexible:

"jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!<rootDir>/node_modules/"
    ],
    "coverageThreshold": {
      "global": {
        "lines": 90,
        "statements": 90
      }
    }
  }

And then change your package.json test script if you're using npm (with yarn you can just append --coverage, for example: yarn test --coverage; however, with npm, it'll just ignore it). So I'd suggest either doing this:

 "test": "react-scripts test --coverage",

Or, I'd recommend using yarn over npm. To install yarn, use one of the following methods.

Working: enter image description here

Matt Carlotta
  • 18,972
  • 4
  • 39
  • 51
  • 1
    Hi! Thanks for answering. I changed the glob pattern, I'm using yarn, and I'm also using Linux Mint (19.1), but for some obscure reason Jest still doesn't collect the coverage: https://i.imgur.com/06ZXQNA.png. – Lual Aug 13 '19 at 00:43
  • 1
    Unfortunately, I can't replicate it. So... my guess is it might be your related to your node_modules folder. Try deleting the node_modules folder and the yarn.lock file. Then reinstall your deps. Or, better yet, clone your repo into another folder, install the deps and try again. This can at least narrow it down to be project-related or OS-related. – Matt Carlotta Aug 13 '19 at 01:19
  • I tried deleting node_modules and then reinstalling and it didn't work. I also tried deleting yarn.lock too, but then I got this error: https://i.imgur.com/qfBEt4S.png, which I tried to solve by reinstalling that particular dependency but it didn't work either. My guess is that it has something to do with some mismatching version of one of the many random dependencies, but both the initial issue and this new one seem to be rabbit holes :/ – Lual Aug 13 '19 at 03:04
  • 1
    Have you tried cloning your repo into a new folder? If not, please do so: 1. Open a terminal on your desktop (or open a terminal and `cd ~/Desktop`), 2. type `git clone git@github.com:lualparedes/lualparedes.github.io.git`, 2. `cd lualparedes.github.io`, 4. `yarn install` and 5. `yarn test --coverage`. If that fails, then I'd recommend uninstalling node and npm completely and then reinstalling it again. – Matt Carlotta Aug 13 '19 at 03:49
  • I tried cloning the repo, and it didn't work. I also tried switching Node versions but it didn't work either, I've tried with v11.7.0 (default version on my computer at the moment) and 10.16 (version used by @Tien Duong), but still no luck. – Lual Aug 14 '19 at 01:04
  • 1
    No idea then. Since it's seems related to your system, I'd recommend the following: 1. Make sure you have enough available RAM (ideally 16GB), 2. Install Linux Mint 19.2 (or reinstall 19.1) and try again. 3. Create a bug report here https://github.com/facebook/jest/issues and include everything above (system specs, include the repo, and what you've tried to remedy the issue, .etc). – Matt Carlotta Aug 14 '19 at 03:16
  • I only have 8GB, but I'm able to collect coverage from a huge work project (200+ test files) in the same machine, and that project has almost the exact same configuration —I literally copied chunks of the config files of that project. I'll probably use this as an opportunity to learn a little bit about Jest internals, but turning the website into a blog is higher in my priority list at the moment. Thanks so much for taking the time to think about the issue and even follow up for several days! :) – Lual Aug 14 '19 at 03:51
  • Why does the src folder appear that low number? I mean shouldn't it be higher? @MattCarlotta – SotoArmando Jun 20 '20 at 00:32
10

What helped me is that instead of

npm run test

or

npm run test --watchall

I did this:

npm run test a

and

npm run test a -- --coverage
omkobass
  • 194
  • 1
  • 10
  • For whatever reason, that actually shows the files for me. But only works by filtering the tests being run. So it's only a hint at what might be the real solution here. – aef Aug 31 '22 at 15:33
4

Been there... You're missing one more parameter in Jest config:

collectCoverage: true
David
  • 623
  • 7
  • 16
3

In our case the problem was with the jest rootDir setting (in our package.json) which we had set to tests. Jest therefore ignored our src/ folder where our actual source code was. The rolution was to tell jest about both folders:

package.json old

"jest": {
  "rootDir: "tests"
}

package.json new

"jest": {
  "roots": [
    "src",
    "tests"
  ]
}
Marc
  • 13,011
  • 11
  • 78
  • 98
3

Seems the problem is with the flag --watchAll Without setting it to false it does not generate coverage

react-scripts test --reporters=jest-junit --reporters=default --coverage --coverageDirectory='testresults/coverage' --coverageReporters=cobertura --coverageReporters=lcov --watchAll=false 
dawid debinski
  • 392
  • 4
  • 6
2

For me, <rootDir> was missing, it worked fine after adding it.

"collectCoverageFrom": [ "<rootDir>/**/*.{js,jsx,ts,tsx}" ]

1

For me, I've changed the folder's name and forgot to update the collectCoverageFrom key under the jest.config.ts file.

A-S
  • 2,547
  • 2
  • 27
  • 37
0

In my case, I was testing React Native/Expo app with the option cacheDirectory: '.jest/cache'. Deleting the .jest directory has solved the issue for me.

Mehmet N. Yarar
  • 576
  • 9
  • 17
0

In my case I was able to get to work by deleting cache and do npm install. In windows cache location (~\AppData\Roaming\npm-cache)

indika
  • 31
  • 4
0

I had a similar problem to yours and these are the solution I found recently. In package.json I have to set the collectCoverageFrom and coverageReporters to:

{   "jest": {
    "collectCoverage": true,
    "coverageReporters": [
        "cobertura",
        "lcov",
        "text"
    ],
    "collectCoverageFrom": [
        "src/**/*.{ts,tsx,js,jsx}",
        "!src/**/*.d.ts"
    ]
}

And since I'm using npm:

npm test --coverage

Btw, I'm using Vite—just in case you're curious.

Tri Dawn
  • 540
  • 6
  • 11
  • **Multiple configurations found:** -> `Implicit config resolution does not allow multiple configuration files. Either remove unused config files or select one explicitly with `--config`.` – Aliton Oliveira Nov 11 '22 at 03:04
0

1º - Try removing your jest.config file.js (if it exists).

2º - Keep the default Jest settings only in your package.json file, so you don't get confused when compiler both settings.

like this:

"jest": {
  "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!((jest-)?react-native|@react-native(-community)?)|expo(nent)?|
      @expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|
      @react-navigation/.*|@unimodules/.*|
      unimodules|sentry-expo|native-base|react-native-svg)"
    ],
    "collectCoverage": true,
    "collectCoverageFrom": [
      "**/*.{ts,tsx,js,jsx}",
      "!**/*/*.d.ts",
      "!**/coverage/**",
      "!**/node_modules/**",
      "!**/babel.config.js",
      "!**/jest.setup.js"
    ]
}

3º - With these settings made, in package.json file, separate the scripts to run the Jest. One for testing and one for collecting Coverage

like this:

"scripts": {
   ...,
   "test": "jest --watch --coverage=false",
   "testWithCoverage": "jest"
}
wylsantos
  • 1
  • 1
0

In Node.js too, adding collectCoverageFrom in package.json helped me to find the uncovered files.

My package.json,

{
  ...
  "jest": {
    "testEnvironment": "node",
    "coveragePathIgnorePatterns": ["/node_modules/", "api-testing"],
    "testPathIgnorePatterns": ["/node_modules/", "api-testing"],
    "collectCoverageFrom": ["**/controllers/*.js"]
  }
}

Before adding collectCoverageFrom

Before adding collectCoverageFrom

After adding collectCoverageFrom

After adding collectCoverageFrom

Basically, without adding collectCoverageFrom, it only includes the files that has test cases (i.e. the .test.js files in the usual naming convent) .

0

I wonder if the "src/**/*.ts*" wildcard pattern you're using to cover .ts and .tsx files might be the problem. I would try this pattern to include both file types:

collectCoverageFrom: ['src/**/*.{ts,tsx}']
dmbaughman
  • 578
  • 2
  • 7
-1

For me the coverage stopped showing just at a random rerun of npm test. What helped me was to change packages.json

from

"test": "react-scripts test --coverage",

to

"test": "react-scripts test",

run npm test

then change back to

"test": "react-scripts test --coverage",

run npm test again -> coverage shown

Viktor
  • 334
  • 1
  • 3
  • 14
-2

Add this to your package.json

"jest": {
    "testPathIgnorePatterns": [
      "<rootDir>/path/to/ignore/"
    ]
  }

This will solve the issue of yours instead of specifying a lot of these commands

Md Irshad
  • 19
  • 4