In this tutorial, you will learn how to configure your build pipeline to generate a test coverage report every time you run your ReactJS based unit tests. Understanding the level of code coverage percentage within your project is very important. Without this information, you will not know how trustable your application's codebase actually is when making changes. You will not need to install any new packages to enable this type of reporting within your project. Jest is the main testing framework used in conjunction with a ReactJS application. As of Jest version 21.2.1, new out-of-the-box code coverage reports now ships with Jest.

Installing Jest

To install Jest, type this command into the terminal:

To enable code coverage, within package.json you will need to pass the --coverage flag into your test script, like so;

As part of this new feature, you can also define a quality gate. You can force Jest to fail a build if the code coverage is below a minimum threshold. My recommendation is to set the code coverage quality gate to around 80-90%. Setting a high code-coverage threshold may cause frustration within the team. Trying to hit a deadline and being blocked by test coverage can be annoying. If you experience this then you can always lower the bar later. In general, it is better to start high and then drop the threshold, rather than start low. In the latter case, trying to raise the bar will result in you having to write hundreds of tests. This effort may then be deemed too much expensive and lengthy and so the bar is left as is.

To configure the code-coverage threshold, create a jest.config.js file in the root of your project. To configure the quality gate, add the coverageThreshold flag and set it accordingly:

Using the config above if the test coverage is less than 90% on all of the functions, branches, lines, and statements then the build will fail. This is something you should do at the start of every project to ensure high quality!

Code Coverage With Jest