Clean β’ Professional
Ensuring your React application works correctly is crucial. Test coverage helps you measure how much of your code is being tested, while reports give you insights into which parts of your application need better testing.
Test coverage measures the percentage of your code executed by tests. It helps identify:
Coverage can include:
if/else) testedJest is the most common testing framework in React applications.
Step 1: Install Jest (if not already installed)
npm install --save-dev jest
Most React apps created with Create React App already include Jest.
Step 2: Run Tests with Coverage
Use the following command:
npm test -- --coverage
Or, for CRA:
react-scripts test --coverage
This generates a coverage summary in your terminal, for example:
-----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------|---------|----------|---------|---------|-------------------
All files | 85% | 75% | 80% | 86% |
Button.jsx | 90% | 80% | 100% | 90% | 12
Login.jsx | 80% | 70% | 75% | 82% | 22, 45
% Stmts β Percentage of statements tested% Branch β Percentage of conditional branches tested% Funcs β Percentage of functions tested% Lines β Percentage of lines testedUncovered Line #s β Lines that werenβt testedStep 3: View HTML Coverage Report
Jest can generate a detailed HTML report for easier inspection:
npm test -- --coverage --coverageReporters=html
After running, open coverage/lcov-report/index.html in your browser to see a color-coded report showing which files and lines are fully tested or missing tests.
if/else, loops, and ternary branchesAutomate coverage checks to ensure new code is tested:
npm test -- --coverage --watchAll=false
Or, in GitHub Actions:
- name: Run tests
run: npm test -- --coverage --watchAll=false
You can fail builds if coverage falls below a threshold:
"jest": {
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 85,
"lines": 90,
"statements": 90
}
}
}