Sub topic 14
Measure coverage and debug failing tests
This chapter assumes you can already write and run a Jest test for a Lightning web component with createElement, query the shadow root, and await re-rendering. It also assumes the sfdx-lwc-jest setup from the earlier chapters. Here you will learn how to find code your tests never run, how to enforce a minimum, and how to work out why a test fails.
What coverage tells you
Coverage is a report of which lines of your source code ran while the tests ran. Jest collects it with Istanbul, a coverage tool built into Jest. It reports four numbers:
| Metric | What it counts | Column | Column |
|---|---|---|---|
| Statements | Individual statements that executed | ||
| Branches | Each side of an `if`, a ternary, `&&`, ` | `, `??`, and each `case` | |
| Functions | Functions and methods that were called at least once | ||
| Lines | Source lines that contained executed code |
Coverage shows what your tests did not execute. It does not show that the tests that did execute check anything useful. A test that renders a component and asserts nothing still raises coverage. Use the report to find gaps, then judge whether each gap matters.
Jest coverage is separate from the Apex coverage rule. Salesforce requires 75% Apex coverage to deploy to production, but it does not check Jest results. Any threshold for LWC tests is your team's decision.
Generate a coverage report
The project from the setup chapter already has a coverage script. This is the relevant part of package.json:
{
"scripts": {
"test:unit": "sfdx-lwc-jest",
"test:unit:watch": "sfdx-lwc-jest -- --watch",
"test:unit:coverage": "sfdx-lwc-jest -- --coverage"
}
}Run it:
npm run test:unit:coverageJest prints a table after the test results. For the counter component it might look like this:
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
counter.js| 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------The last column lists the lines that never ran. For a component with gaps, it shows ranges such as 14-18,27. Open those lines and ask which test would reach them.
Jest also writes files to a coverage folder in the project root. Open coverage/lcov-report/index.html in a browser to see each source file with executed lines in green and missed lines in red. Branches that never ran are marked separately. Add coverage to .gitignore so you do not commit the generated files.
Choose which files are measured
By default Jest only reports on files that at least one test imported. A component with no test file is missing from the table, so overall coverage looks better than it is. Set collectCoverageFrom to list every file you want measured, and add a threshold to the same config file.
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
modulePathIgnorePatterns: ['<rootDir>/.localdevserver'],
collectCoverageFrom: [
'force-app/main/default/lwc/**/*.js',
'!**/__tests__/**',
'!**/__mocks__/**'
],
coverageThreshold: {
global: {
statements: 80,
branches: 70,
functions: 80,
lines: 80
}
}
};The patterns starting with ! exclude test files and manual mocks, which are not production code. With collectCoverageFrom set, untested components now appear in the table with 0%.
When a threshold is not met, Jest prints a message such as Jest: "global" coverage threshold for branches (70%) not met: 62.5% and exits with a non-zero status. A continuous integration job can fail the build on that exit code. Jest only checks thresholds when coverage is collected, so the threshold has no effect on npm run test:unit.
Branch coverage usually lags behind the other numbers. It is also the number that most often points to a real missing test, such as an error path or an empty-list case.
Close a coverage gap
Suppose the counter gets a guard against a negative step:
import { LightningElement, api } from 'lwc';
export default class Counter extends LightningElement {
@api step = 1;
count = 0;
handleClick() {
if (this.step < 0) {
return;
}
this.count += this.step;
this.dispatchEvent(
new CustomEvent('countchange', { detail: { count: this.count } })
);
}
}The earlier test only uses step = 2, so the return line is uncovered and the branch metric drops below 100. The report points to that line. Add a test that takes the other path:
it('ignores clicks when the step is negative', async () => {
const element = createElement('c-counter', { is: Counter });
element.step = -1;
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener('countchange', handler);
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('0');
expect(handler).not.toHaveBeenCalled();
});This test asserts a behavior, not only that the line ran. That is the difference between a covered line and a tested one.
Debug a failing test
Most failures in LWC tests come from a small set of causes. Work through them in this order.
flowchart TDReplace the above: see the diagram below.
Read the error first
Jest prints the failing assertion, the expected and received values, and a code frame with the line. Many failures are explained there. Two messages are worth recognizing:
Cannot find module '@salesforce/apex/ContactController.getContacts'means the import has no mock. Add ajest.mockcall with{ virtual: true }, as in the Apex mocking chapter.Cannot read properties of null (reading 'textContent')meansquerySelectorfound nothing. The element is missing, the selector is wrong, or the component has not re-rendered yet.
Print what the component rendered
When a query returns null, look at the real output instead of guessing:
it('shows the count after a click', async () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
element.shadowRoot.querySelector('button').click();
console.log(element.shadowRoot.innerHTML);
await Promise.resolve();
console.log(element.shadowRoot.innerHTML);
expect(element.shadowRoot.querySelector('.count').textContent).toBe('1');
});The first log still shows 0 and the second shows 1. That comparison shows that rendering happens after the awaited microtask, which is the most common cause of "the value is stale" failures. Remove the console.log calls once you have found the problem.
Components that render child components show those children as unexpanded custom elements, such as <c-child>, or as base component stubs. Their inner content does not appear in the parent's shadow root. Query the child's own shadowRoot if you need it.
Run fewer tests
Narrowing the run makes the output readable. Arguments after the -- go to Jest:
# Run one test file
npx sfdx-lwc-jest -- force-app/main/default/lwc/counter
# Run tests whose names match a pattern
npx sfdx-lwc-jest -- -t "negative"
# Show each test name with its result
npx sfdx-lwc-jest -- --verboseYou can also change it to it.only or it.skip while investigating. Remove those before committing, because it.only silently hides every other test in the file.
Check for leaked state
A test that passes alone and fails in the full run usually depends on state left behind by an earlier test. Look for these causes:
- The
afterEachthat clearsdocument.bodyis missing, so queries find elements from a previous test. - Mock return values were set in one test and not reset. Call
jest.clearAllMocks()inafterEach, orjest.resetAllMocks()if you also want to remove the implementations you set. - A
setTimeoutor promise from one test finishes during the next.
To confirm, run the failing file alone and then the whole suite. If the results differ, the cause is shared state.
Attach a debugger
For problems that logging does not explain, you can pause the test and step through the code. Add a script that starts Node in inspect mode:
{
"scripts": {
"test:unit:debug": "sfdx-lwc-jest --debug"
}
}Put a debugger; statement inside the component or the test, run npm run test:unit:debug, and open chrome://inspect in Chrome. The --debug option runs tests in a single process and waits for a debugger to attach, so tests run one at a time. In Visual Studio Code you can instead use the Salesforce Extension Pack's "Debug Test" lens above each it block, which starts the same kind of session.
Run tests in watch mode while you fix them
npm run test:unit:watch reruns tests related to changed files whenever you save. Combined with -t or a file path, it gives quick feedback while you change a test or a component.
Exercises
Exercise
A coverage run shows 100% for statements, functions, and lines, but 75% for branches on a component that has if (this.items.length === 0) { return; }. What does this tell you, and how do you fix it?
Show answer
Every line ran, but one side of a condition never did. Your tests probably only cover the case where items is not empty (or only the empty case). Add a test that sets items to the other state, and assert on the resulting output. Branch coverage rises once both sides of the if have run.
Exercise
A test passes when you run npx sfdx-lwc-jest -- -t "adds the step" but fails when you run the whole file. Name two likely causes and one check for each.
Show answer
Likely causes are (1) DOM left over from an earlier test, because the afterEach that removes children from document.body is missing or incomplete, and (2) a mock that keeps its return value or call count from an earlier test. For the first, log document.body.innerHTML at the start of the failing test and look for extra components. For the second, add jest.clearAllMocks() in afterEach and check whether the failure disappears.