Sub topic 12
Keeping tests isolated
This chapter assumes you can already write a basic component test with createElement. It also assumes you know how to mock a wired Apex method and an imperative Apex call, and that you are comfortable with async/await. Here you will learn what state survives from one test to the next, and how to reset it so each test starts clean.
Why isolation matters
Each it block should pass or fail on its own. You should be able to run it alone with it.only, run the file in a different order, or add a new test above it, and the result should not change.
LWC Jest tests share more state than they appear to. Within one test file, all tests share:
- The
documentobject and everything attached todocument.body. - Every module-level mock, such as
jest.fn()instances and test wire adapters. - Any variable you declared at the top of the file.
- Timers, if you replaced them with fake timers.
Jest gives each test file a fresh module registry and a fresh jsdom, so files do not affect each other. Tests inside one file do.
A leak between tests usually shows up as a test that passes alone and fails in the full run. It can also pass only because an earlier test left the right data behind, which hides a real bug.
What leaks, and how to reset it
| Shared state | How it leaks | Reset with |
|---|---|---|
| Elements in `document.body` | A component from test A is still connected during test B | Remove all children in `afterEach` |
| `mock.calls` and `mock.results` | `toHaveBeenCalledTimes(1)` counts calls from earlier tests | `jest.clearAllMocks()` |
| Mock implementations | `mockResolvedValue` from test A answers test B | `jest.resetAllMocks()`, or set a value in every test |
| Test wire adapter instances | `emit` reaches every connected component using that adapter | Disconnect components by removing them from the DOM |
| Fake timers | Later tests run with fake `setTimeout` | `jest.useRealTimers()` |
| Variables in the file scope | One test changes an object that another reads | Build fresh data in each test |
Cleaning up the DOM
Every example in this tutorial attaches the component to document.body. Nothing removes it unless you do. The standard cleanup is:
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});Removing the element does more than tidy the page. It disconnects the component, which runs its disconnectedCallback. It also disconnects the component's wire from the adapter.
This matters for test wire adapters. When you call emit on a test adapter, the data goes to every component instance currently connected to that adapter. Suppose test A leaves a c-contact-list in the DOM. In test B you create another one and call getContactList.emit([...]). Both components receive the data. If your assertion uses document.body.querySelector or counts elements, the leftover component can make it pass or fail for the wrong reason.
Resetting mocks
Jest offers three reset levels. They differ in what they erase.
| Call | Clears call history | Removes implementations and return values |
|---|---|---|
| `jest.clearAllMocks()` | Yes | No |
| `jest.resetAllMocks()` | Yes | Yes |
| `jest.restoreAllMocks()` | Yes | Restores spied originals only. It does not affect plain `jest.fn()` mocks the way `resetAllMocks` does. |
The difference between the first two is a common source of leaks. Consider this test file for an imperative Apex call:
import { createElement } from 'lwc';
import ContactSearch from 'c/contactSearch';
import findContacts from '@salesforce/apex/ContactController.findContacts';
jest.mock(
'@salesforce/apex/ContactController.findContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-search isolation', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('shows results when Apex resolves', async () => {
findContacts.mockResolvedValue([{ Id: '001', Name: 'Amy Taylor' }]);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
});
it('shows no results when nothing is configured', async () => {
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
// Passes or fails depending on the previous test.
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});
});The second test configures nothing. Because clearAllMocks keeps implementations, findContacts still resolves with Amy Taylor, and the test sees one list item. Run it alone and findContacts returns undefined, so the result differs.
Two fixes work:
- Replace
jest.clearAllMocks()withjest.resetAllMocks()inafterEach. - Set the mock value explicitly in every test, including the empty case:
findContacts.mockResolvedValue([]).
The second fix is better as a habit, because the test then states its own precondition. Use both when you can.
Resetting wire-based tests
Test wire adapters made with createApexTestWireAdapter(jest.fn()) hold an inner jest.fn(). resetAllMocks resets that function too, which is what you want. The adapter itself keeps working, because the wire connection is rebuilt each time a component connects.
Emitted data is not stored for later components. A new component starts with no data until you call emit again. Each test therefore has to emit its own data after appending the element:
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
import getContactList from '@salesforce/apex/ContactController.getContactList';
jest.mock(
'@salesforce/apex/ContactController.getContactList',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
function mountList() {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
return element;
}
describe('c-contact-list isolation', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.resetAllMocks();
});
it('renders contacts', async () => {
const element = mountList();
getContactList.emit([{ Id: '001', Name: 'Amy Taylor' }]);
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
});
it('renders the error state', async () => {
const element = mountList();
getContactList.error();
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
});
});The mountList helper builds a new element for every test. Do not create the element once at the top of the file and share it. A shared element carries rendered state, event listeners, and wire data from one test into the next.
Build fresh test data
A constant such as const MOCK_CONTACTS = [...] at the top of the file is convenient. It is also shared. If the component or the test mutates it, for example by sorting the array in place, later tests see the changed data. Two ways to avoid this:
- Return a new array from a function:
const buildContacts = () => [{ Id: '001', Name: 'Amy Taylor' }]; - Copy the data when you emit it:
getContactList.emit(JSON.parse(JSON.stringify(MOCK_CONTACTS))).
The LWC engine freezes (makes read-only) data that a component receives through @wire and @api. Your own constant is not frozen until it has been passed to a component. This is another reason to prefer a fresh copy per test.
Timers and pending promises
If a test uses fake timers, restore real ones afterward. Otherwise flushPromises, which depends on setTimeout, will hang in the next test:
afterEach(() => {
jest.useRealTimers();
});A pending promise is a second kind of leak. Suppose a test clicks a button that starts an Apex call and finishes its assertions before the promise settles. The .then handler runs later, possibly during the next test, and may call console.error or update a component that was already removed. Always await flushPromises() after the action that starts async work, even when the assertion does not need the result.
Avoid `jest.resetModules` in component tests
jest.resetModules() clears the module registry. After that, import ContactList from 'c/contactList' at the top of the file points to an old copy of the module, while any require inside a test loads a new copy. The mocks you imported at the top may no longer be the ones the component uses. You can fix this by using require throughout, but the code gets harder to read. Prefer resetting mock state over resetting modules.
The lifecycle of an isolated test
Checking that your tests are isolated
Run these three checks on any test file you write:
- Run each test alone with
it.only. Every test should pass. - Run the whole file, then reverse the order of the tests. Everything should still pass.
- Search for
toHaveBeenCalledTimesassertions and confirm the count would be right if the test ran first.
You can also run npx jest --runInBand --randomize on Jest 29.2 or later to shuffle test order inside each file. A failure that appears only under shuffling points to shared state.
Summary of habits
- Create the element inside each test or through a helper. Never share one across tests.
- Remove every child of
document.bodyinafterEach. - Reset mocks in
afterEach, or setresetMocks: truein the Jest config. - Set the mock value in every test, including the empty and error cases.
- Build fresh data for each test.
- Restore real timers and flush promises before a test ends.
Exercise
A test file has two tests for a component that calls findContacts imperatively. Test 1 calls findContacts.mockResolvedValue([{ Id: '001' }]). Test 2 does not configure the mock and expects an empty list. afterEach calls jest.clearAllMocks(). Test 2 fails when the whole file runs but passes with it.only. Why, and what are two ways to fix it?
Show answer
clearAllMocks erases call history but keeps implementations, so the resolved value from test 1 still answers test 2. Fix it by using jest.resetAllMocks() in afterEach (or resetMocks: true in the Jest config), or by setting findContacts.mockResolvedValue([]) explicitly in test 2.
Exercise
Test A mounts a c-contact-list and never removes it. Test B mounts another c-contact-list and calls getContactList.emit(data). Why might test B's assertions behave unexpectedly, and what single change prevents it?
Show answer
emit delivers data to every component instance still connected to the test wire adapter, so the leftover element from test A receives the data as well. Removing all children of document.body in afterEach disconnects the component and its wire, so only test B's element receives the data.