Sub topic 7
Clean up between tests
This chapter assumes you can write a basic Jest test for a Lightning web component with createElement, and that you know describe, it, and afterEach. It covers why tests must not share state and how to enforce that.
Why isolation matters
When you call document.body.appendChild(element), the component stays in the shared jsdom document. Jest runs every test in a file against the same document. If a test does not remove its component, the next test starts with that leftover element in the page.
Leftover state causes errors that are hard to trace:
- A query such as
document.querySelector('c-counter')returns the element from an earlier test. - A component that is still connected keeps listening for events and can run code during later tests.
- Mock call counts carry over, so
toHaveBeenCalledTimes(1)fails or passes for the wrong reason. - A test passes when run alone and fails when run with the whole file, or the reverse.
Each test should start from a known state and leave nothing behind.
Remove elements in afterEach
The standard pattern removes every child of document.body. Put it in an afterEach hook so it runs even when a test fails.
import { createElement } from 'lwc';
import Counter from 'c/counter';
describe('c-counter', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('starts at zero', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
expect(element.shadowRoot.querySelector('.count').textContent).toBe('0');
});
it('starts at zero again in a fresh component', () => {
const element = createElement('c-counter', { is: Counter });
document.body.appendChild(element);
expect(document.body.children).toHaveLength(1);
});
});The second test checks that document.body holds exactly one element. Without the cleanup hook, it would find two.
Removing the element from the document also triggers its disconnectedCallback. This is useful when the component registers listeners or subscriptions and you want to confirm it releases them.
Reset mocks
Mock functions keep their call history across tests in the same file. Clear them in the same hook.
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});Jest offers three related functions. Choose by what you need to reset.
| Function | Clears call history | Removes mock implementations |
|---|---|---|
| `jest.clearAllMocks()` | Yes | No |
| `jest.resetAllMocks()` | Yes | Yes |
| `jest.restoreAllMocks()` | Yes | Yes, and restores originals for `jest.spyOn` mocks |
Use clearAllMocks when a jest.mock factory defines the default behavior you want to keep. Use resetAllMocks when each test sets its own return values and should not inherit the last one.
Move shared setup into a helper
If several tests build the component the same way, put the setup in a function instead of a shared variable. A function returns a new element each time, so tests cannot share one.
function createCounter(props = {}) {
const element = createElement('c-counter', { is: Counter });
Object.assign(element, props);
document.body.appendChild(element);
return element;
}Avoid declaring let element at the top of the describe block and assigning it in beforeEach unless you also reset it. A stale reference to a removed element is a common source of confusing failures.
Common mistakes
- Putting cleanup in
afterAll. It runs once per file, so tests in between still share the document. - Cleaning up at the start of a test only. A failing test then leaves state for the next file's reader to debug. Prefer
afterEach. - Removing only the element you remember. Looping over
document.body.firstChildalso removes elements added by other helpers. - Relying on test order. If a test needs another test to run first, it is not isolated.
Exercise
A test file has three tests that each append a c-counter to the document. The file has no afterEach hook. The third test asserts that document.querySelectorAll('c-counter') has length 1, and it fails. What is the cause, and what two things belong in the fix?
Show answer
The first two tests left their elements in the shared document, so the third test finds three. Add an afterEach hook that removes every child of document.body with a while (document.body.firstChild) loop. In the same hook, call jest.clearAllMocks() so mock call counts do not carry over either.