Jest code coverage report explained
Your app’s code coverage is what percentage of the code is currently covered by unit tests. In this post I will explain how we can generate a code coverage report with Jest in your command line, as well as a visual HTML report.
Calculating your code coverage in Jest
Seeing your code coverage can be as simple as adding the --coverage
flag when running your Jest unit tests:
Using npm or yarn:
After you run the coverage command you’ll get a summary report that looks like this:
Generating a Jest code coverage report with HTML
When looking at the summary table, it can be very hard to determine where you are missing coverage. You can also generate a code coverage report using HTML.
Using npm or yarn:
This command will generate a report in the folder you specified with --coverageDirectory
. (In the above example, it would create a folder called coverage
).
If you open up the index.html file in your browser, you will see lines highlighted in red.
These are the lines that are not currently covered by your unit tests.
How to track untested files with Jest’s code coverage report
By default, Jest will calculate coverage for each file that has a test (and any files that they are importing).
This means that if you had the following files:
Foo.js
Foo.test.js
(tests the code fromFoo.js
)Bar.js
Even though Bar.js
doesn’t have any unit tests, this won’t decrease the code coverage.
Jest will report that you have 100% code coverage!
By adding —collectCoverageFrom, Jest will calculate code coverage for all the files that you specify. Even ones without any tests.
How can you get 100% code coverage?
Simply, you would have to go through the report, find all the red lines, and ensure that you have test cases that cover these components.
However, sometimes it will be too hard to cover certain lines of code with unit tests. Spending your time trying to find a workaround to cover that line of code is never worth it. I believe there are much better things you could be spending your time on than striving for 100% coverage!
Even if you do “cover” a line of code, there’s no guarantee that it will be perfect and bug-free, either. If we take a look at a double function that doubles the number you pass in:
If you wrote a test like:
The test would pass, and you would get 100% code coverage, since you technically tested it. However it doesn’t really mean anything - your code would fail as soon as you tried double(2)
, for example.
Code coverage is useful, but it’s not going to mean your code is perfect, and it’s important not to use it as the only metric to measure your unit tests. Make sure to keep in mind all the possible edge cases and different scenarios, as code coverage won’t pick these up.