Jest watch with code coverage not working
Asked Answered
S

3

10

I'm trying to run jest --coverage --watch so that I only get the coverage for whatever component I'm writing tests for and I can see the increased coverage as I write more tests. But while the modified tests are successfully picked up and run, the coverage report comes up empty.

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |        0 |        0 |        0 |        0 |                   |
----------|----------|----------|----------|----------|-------------------|


Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.599s
Ran all test suites related to changed files.

The documentation on this is almost zero, but it seems like it should work according to this pr: https://github.com/facebook/jest/pull/5601

Shanleigh answered 18/10, 2019 at 8:28 Comment(0)
S
5

Here is a solution Create a jest.config.js and add the following content

  • jest.config.js
module.exports = {
    collectCoverage: true,
    coverageReporters: [
        "html"
    ]
};

And in package.json:

"scripts": {
    "test": "jest --watchAll"
}
Scrimmage answered 5/1, 2021 at 5:20 Comment(0)
H
2

I would you use jest --watchAll --coverage rather then set it in a config file because you may not want to collect coverage every time you run jest. You can add it as a run script or a bash alias as well if you use it frequently.

Hydrograph answered 12/4, 2022 at 15:26 Comment(0)
L
0

Using NX

I had the exact same issue when using nx test my-lib and the solution was to pass both --watch AND --watchAll:

nx test my-lib --watch --watchAll

This runs and generates the coverage for all files indeed.

This works having in my jest.config.ts something like:

export default {
  // ...
  codeCoverage: true,
  collectCoverage: true,
  coverageDirectory: '../../../coverage/libs/path/to/my-lib',
  coverageThreshold: {
    global: {
      statements: 100,
      branches: 100,
      lines: 100,
      functions: 100,
    },
  },
};
Lac answered 20/6 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.