Jest is a testing framework built by developers at Facebook, to help developers write unit tests and ship code with confidence.
Let's learn how to setup and configure jest to run unit tests for your react code and create a code-coverage report.
Step 1. Create a jest config at the root of your project.
// src/jest.config.js module.exports = { "setupFiles": ["./src/setupTests.js"], "testRegex": "/*.test.js$", "collectCoverage": true, "coverageReporters": ["lcov"], "coverageDirectory": "coverage", "coverageThreshold": { "global": { "branches": 80, "functions": 80, "lines": 80, "statements": 80 } }, "moduleDirectories": ["src"] }
setupFiles
- A list of paths to modules that run some code to configure or set up the testing environment.collectCoverage
- A boolean indicating whether a coverage report should be collected or not.coverageReporters
- A list of reporter names that Jest uses when writing coverage reports. Default values are["json", "lcov", "text", "clover"]
coverageDirectory
- The directory where Jest should output its coverage files.coverageThreshold
- This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as global, as a directory or file path. If thresholds aren't met, jest will fail.
Step 2. Configure your scripts in package.json
{ "scripts": { "test": "react-scripts test", "test:coverage": "yarn run test --coverage --silent --watchAll=false" "build": "yarn run test:coverage && set GENERATE_SOURCEMAP=false && react-scripts build" } }
--coverage
flag asks Jest to collect a code-coverage report.--watchAll=false
disables the watch mode to make sure the process exits after running all tests instead of listening to file changes. Note that this is usually handled for you on most CI environments.--silent
runs the test in silent mode ignoring console logs and warnings.
That’s all folks 🥳.
Now you're good to test and create code-coverage reports for your unit tests.
cd project_name yarn run test:coverage # now open coverage/lcov_reports/index.html on your browser