In this tutorial, you will learn how to enable the test code coverage functionality into your React.js application. Enabling code coverage into the build is very powerful as it ensures that tests are included as new code is written. Jest version 21.2.1 or higher comes with a really handy code coverage feature. As Jest is the main testing framework used in conjunction with React then let's start there.
To install Jest, type this command into the terminal:
To enable code coverage you will need to pass the --coverage flag into your test script within package.json. Below shows how you can add the flag into your project:
Before adding code coverage to build, you will want to configure the minimum code coverage requirements. My recommendation is to set the code-coverage for everything to around 80-90%. Setting a high code-coverage threshold can developers to feel frustration when working. If that's the case then you can always start to lower the bar. In general, it's better to start high and then drop the threshold, rather than start low and then end up having to write hundreds of tests in one if you suddenly decide to raise the bar.
To configure the code-coverage threshold, create a jest.config.js file in the root of your project. In here you will want to add the
coverageThresholdflag and set it accordingly:
Using the config above if the code coverage setting above, if less than 90& of the functions, branches, lines and statements are not covered by tests then the build will fail.