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.
Seeing your code coverage can be as simple as adding the
--coverage flag when running your Jest unit tests:
yarn test folder/name --coverage
After you run the coverage command you’ll get a summary report that looks like this:
When looking at the summary table, it can be very hard to determine where you are missing coverage!
A much easier way is to create a visual code coverage report:
yarn test folder/name --coverage --coverageDirectory='coverage'
This command will generate an HTML report in the folder you specified with
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.
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.test.js(tests the code from
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.
yarn test folder/name --coverage --collectCoverageFrom='folder/name/**/*.js'
As you increase your code coverage, 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. 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:
const double = (number) => 2;
You could test that
double(1) = 2 and that test would pass. You would have 100% code coverage as well. But your function would fail with all other numbers.
Code coverage is useful, but 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.