Sub topic 7
Clean up between tests
This chapter covers why Lightning web component (LWC) tests need cleanup, how to do it, and which kinds of shared state leak between tests. It assumes you can already render a component with createElement, query its shadow root, and wait for re-rendering with await Promise.resolve(). It also assumes you know the basics of describe, it, and expect.
Why isolation matters
Each Jest test file runs in its own jsdom environment. Tests inside one file share that environment. When one test appends a component to document.body and never removes it, the next test starts with that component still attached.
Leaked state causes failures that are hard to trace:
- A test passes when run alone and fails when run with the rest of the file.
- A test fails only after you reorder or add a test.
- A query such as
document.body.querySelector('c-counter')returns the element from an earlier test. - A mock reports more calls than the current test made.
The goal is that every test starts from the same known state, whatever ran before it.
Remove components from the DOM
Components created with createElement are not attached until you call document.body.appendChild. Once attached, they stay there. Removing them also triggers the component's disconnectedCallback, which is how you release listeners and timers inside the component.
The standard pattern is an afterEach hook that empties the body:
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders a count of 0 initially', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
expect(element.shadowRoot.querySelector('.count').textContent).toBe('0');
});
it('starts from 0 again in a second test', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
expect(document.body.children).toHaveLength(1);
expect(element.shadowRoot.querySelector('.count').textContent).toBe('0');
});
});The second test checks document.body.children to prove the first test's element is gone. Without the afterEach, that assertion would fail because the body would hold two elements.
You may see document.body.innerHTML = '' as a shorter version. It detaches the elements, but it is less explicit and the loop is the pattern used in Salesforce's own examples. Use the loop so your tests match what other LWC developers expect.
Why a loop and not `removeChild(element)`
A test might create several elements, or a component might add siblings to the body, such as a modal host. Removing only the element you created in the test misses those. Emptying the body covers every case without each test tracking its own elements.
Choose the right hook
Jest offers four lifecycle hooks. Each suits a different kind of setup.
| Hook | Runs | Typical use in LWC tests |
|---|---|---|
| `beforeEach` | Before every test in its `describe` block | Reset mock return values, set up fake timers |
| `afterEach` | After every test in its `describe` block | Empty `document.body`, clear mocks, restore timers |
| `beforeAll` | Once before the first test | Rarely needed. Expensive read-only setup |
| `afterAll` | Once after the last test | Rarely needed. Restore global patches |
Prefer afterEach for DOM cleanup. afterAll would clean up only once, so every test except the first would still see leftovers from the one before it.
Hooks placed inside a nested describe run in addition to the hooks of the outer block. Outer beforeEach hooks run first. Outer afterEach hooks run last. This lets you put DOM cleanup at the top of the file and add scenario-specific setup in nested blocks.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
describe('with a custom step', () => {
let element;
beforeEach(() => {
element = createElement('c-counter', { is: Counter });
element.step = 5;
document.body.appendChild(element);
});
it('adds 5 on click', async () => {
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.count').textContent).toBe('5');
});
});
});The outer afterEach still runs after the nested test. A fresh element is created in each beforeEach, so no test reuses another test's instance.
Reset mocks
DOM cleanup does not touch mock functions. A jest.fn() keeps its recorded calls and any configured return value until you reset it. Jest provides three related functions, and they differ in what they clear:
| Function | Clears call history | Removes configured return values and implementations |
|---|---|---|
| `jest.clearAllMocks()` | Yes | No |
| `jest.resetAllMocks()` | Yes | Yes |
| `jest.restoreAllMocks()` | Yes, for spies | Restores the original implementation of spies created with `jest.spyOn` |
For a mocked Apex method, clearAllMocks is usually enough when each test sets its own return value with mockResolvedValue. Use resetAllMocks when you want a test that forgets to configure the mock to fail loudly (the mock then returns undefined) instead of silently reusing the previous test's data.
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});Be careful with resetAllMocks when the mock factory in jest.mock provides the default implementation. Resetting removes it, and later tests get undefined where they expected the factory's value. If you rely on factory defaults, use clearAllMocks and set return values explicitly in each test.
You can also set clearMocks: true or resetMocks: true in jest.config.js. That applies the reset to every test file in the project. It removes the repeated line from each file, but it hides the behavior from anyone reading a single test, so many teams keep the call in the test file.
Restore timers and globals
Other shared state lives outside the DOM and outside mock functions.
Fake timers. If a test calls jest.useFakeTimers(), switch back in the same test file or the next test inherits the fake clock:
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.runOnlyPendingTimers();
jest.useRealTimers();
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});Running pending timers before switching back stops a debounce or setTimeout inside the component from firing later during an unrelated test.
Globals you patch. If a test replaces window.open, console.error, or navigator.clipboard, restore the original. A spy makes this simple:
let errorSpy;
beforeEach(() => {
errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
errorSpy.mockRestore();
});If you assign over the global directly (window.open = jest.fn()), store the original first and put it back in afterEach. Otherwise every later test in the file uses your stub.
Module-level variables in your test file. A variable declared at the top of the file and changed by a test, such as an array of captured events, persists. Declare it inside beforeEach or reset it there.
Module state inside the component
Jest caches each imported module for the lifetime of a test file. If your component module holds state outside the class, such as a cache in a const at the top of the file, that state survives from one test's component to the next. Removing the element from the DOM does not reset it.
For example:
// force-app/main/default/lwc/lookupCache/lookupCache.js
const cache = new Map();
export function getCached(key, load) {
if (!cache.has(key)) {
cache.set(key, load());
}
return cache.get(key);
}A test that populates cache changes what the next test sees. To get a clean module per test, use jest.resetModules() and re-import inside the test with require, or use jest.isolateModules. Note that after jest.resetModules(), a freshly imported lwc module is a different instance from the one you imported at the top of the file. Import createElement and the component in the same isolated scope so they come from the same module registry.
it('does not share the cache between tests', () => {
jest.isolateModules(() => {
const { createElement } = require('lwc');
const Lookup = require('c/lookup').default;
const element = createElement('c-lookup', { is: Lookup });
document.body.appendChild(element);
expect(element.shadowRoot.querySelector('.result')).toBeNull();
});
});Reach for this only when module state is the actual problem. In most components, state lives on the instance and a fresh createElement call is enough. If you find yourself isolating modules often, consider moving the cache into the component class.
Common mistakes
- Cleaning up in
afterAll. Only the last test benefits. UseafterEach. - Cleaning up only at the end of the test body. If an assertion throws, the cleanup line is skipped and the leak reaches the next test. Hooks run even when a test fails.
- Reusing one
elementvariable across tests. Create the element inside each test or inbeforeEach. - Relying on
document.body.querySelectorto find your component. If cleanup fails, you may query a stale element. Use the reference returned bycreateElementinstead. - Forgetting that
clearAllMockskeeps return values. AmockResolvedValuefrom an earlier test can leak into a test that expects the default. - Resetting mocks that a
jest.mockfactory configured.resetAllMocksremoves those defaults.
Verify that cleanup works
You can assert on the cleanup itself. A test at the start of each describe block that checks document.body.children has length zero before creating anything catches a missing hook early. Jest also runs tests in a file in the order they are defined by default, so a leak often appears in the test right after the one that caused it. If you suspect order dependence, run the file with --randomize (available in Jest 29.2 and later) to shuffle the tests and expose hidden coupling.
Exercise
A test file has two tests. The first creates a c-counter, appends it to document.body, and clicks the button once. The second creates a new c-counter, appends it, and runs document.body.querySelector('c-counter').shadowRoot.querySelector('.count').textContent. The file has no afterEach. What does the second test read, and what two changes make it reliable?
Show answer
It reads the count from the first test's element, because querySelector returns the first matching element in the body, and that element still shows the count after one click. Two changes fix it: add an afterEach that removes every child of document.body, and query through the reference returned by createElement (element.shadowRoot...) instead of searching the body.
Exercise
A test file uses jest.mock with a factory that returns { default: jest.fn() } for an Apex method. Each test calls getContacts.mockResolvedValue(...). Which function belongs in afterEach, jest.clearAllMocks() or jest.resetAllMocks(), and what does the other one change?
Show answer
Both work here, because the factory's default is a bare jest.fn() and each test sets its own return value. clearAllMocks only clears recorded calls. resetAllMocks also removes configured return values and implementations, so a test that forgets mockResolvedValue gets undefined instead of the previous test's data. If the factory had supplied a useful default implementation, resetAllMocks would delete it, and clearAllMocks would be the safe choice.