Search code examples
jestjscode-coverage

Jest test coverage gives 100% coverage for modules that have no tests at all


I'm experiencing 2 issues with Jest test coverage:

1- Jest reports 100% (Stmts, Branch, Func, and Lines) coverage for modules with no tests at all but required by tested modules

2- Jest reports 100% Branch coverage for modules with no tests nor required by tested modules

In the image:

  • sum is a tested module
  • toNum is not tested but required by sum
  • sub is neither tested nor required by tested modules

I've create a repo that reproduces the issue: https://github.com/hossamnasser938/Reproduce-Jest-Coverage-Issue

Here is my package.json: enter image description here

Here is my folder structure: enter image description here

How do I remove the entry for sub.js from the coverage report? I really appreciate your help.jest test coverage


Solution

  • 1- Jest reports 100% (Stmts, Branch, Func, and Lines) coverage for modules with no tests at all but required by tested modules

    This is expected behavior when you configure Jest to collect coverage. The required modules are still executed by your test, despite them not having a test of their own. The documentation for collectCoverage states

    this retrofits all executed files with coverage collection statements

    Your test is executing all of the code from the required module, so the module is covered completely, 100% by your test code. Even though the module is executed by another test, you should still write a separate test for the required module to ensure it works in isolation as a unit.

    2- Jest reports 100% Branch coverage for modules with no tests nor required by tested modules

    Again this is expected behavior given your configuration value for collectCoverageFrom which includes sub.js, and your implementation of sub which has no branching, so Branch statements would be 100% executed (because there are none).

    If you want Jest to stop reporting on sub.js then you have a couple of options:

    • Remove the configuration for collectCoverageFrom entirely, and that will remove the entry for sub.js from the coverage report table.

    • Modify your value for collectCoverageFrom to specifically ignore sub.js:

      collectCoverageFrom: ['src/**/*.js', '!src/**/sub.js']
      

    Personally, I would leave everything as-is to serve as a reminder that sub.js still needs to be tested with adequate coverage.