Sub topic 12
Keeping tests isolated
This chapter assumes you can write a basic LWC Jest test with createElement, and that you know how to mock an imperative Apex import with jest.fn(). It also assumes you have seen test wire adapters and emit.
Why isolation matters
Jest runs every it block in the same test file inside one shared environment. That environment includes one document, one set of module mocks, and one copy of each imported mock function. If a test leaves something behind, the next test inherits it.
Two kinds of leftovers cause most failures:
- Components still attached to
document.body. - Mock state, meaning recorded calls and configured return values.
A test that passes alone but fails after another test is almost always a sign of one of these.
The test lifecycle
Clean up the DOM
A component that stays in the DOM stays connected. Its wire adapters keep listening, so a later emit call reaches both the old component and the new one. Remove every element after each test:
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});Removing the element runs its disconnectedCallback and disconnects its wires.
Clear or reset mocks
Jest offers three ways to clean a mock, and they differ in what they keep.
| Call | Clears recorded calls | Removes configured return values |
|---|---|---|
| `jest.clearAllMocks()` | Yes | No |
| `jest.resetAllMocks()` | Yes | Yes |
| `jest.restoreAllMocks()` | Yes | Only for spies made with `jest.spyOn` |
The middle column matters most. mockResolvedValue on an imperative Apex mock survives clearAllMocks. If test A sets a resolved value and test B forgets to set one, test B silently uses A's value. resetAllMocks removes that risk, so reset in beforeEach and set the value you need inside each test.
A complete isolated test file
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));
function mountComponent() {
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
return element;
}
describe('c-contact-search isolation', () => {
beforeEach(() => {
jest.resetAllMocks();
});
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows one result', async () => {
findContacts.mockResolvedValue([{ Id: '001', Name: 'Amy Taylor' }]);
const element = mountComponent();
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
expect(findContacts).toHaveBeenCalledTimes(1);
});
it('starts with no calls and no results', async () => {
findContacts.mockResolvedValue([]);
const element = mountComponent();
await flushPromises();
expect(findContacts).not.toHaveBeenCalled();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});
});The second test checks not.toHaveBeenCalled(). It would fail without the reset in beforeEach, because the first test already called the mock once.
The mountComponent helper also keeps setup in one place. Each test gets a fresh element and no test shares one.
Avoid shared mutable state
Keep these habits:
- Create the element inside each
it, or inside a helper that eachitcalls. Do not create it once at the top of the file. - Declare mock data inside the test, or freeze it with
Object.freeze. A component that mutates a shared array will change the data for later tests. - Do not rely on test order. Run a single test with
it.onlyto confirm it passes by itself.
Common errors
- Calls from an earlier test appear in
toHaveBeenCalledWith. Mocks were never cleared. Addjest.resetAllMocks()tobeforeEach. - A wire
emitrenders twice or in the wrong element. An earlier component is still attached. Add the DOM cleanup toafterEach. - A mock returns
undefinedafterresetAllMocks. The reset removed the value you set in an earlier hook. Set values inside the test, after the reset.
Exercise
A test file calls jest.clearAllMocks() in afterEach. Test 1 uses findContacts.mockResolvedValue([{ Id: '001' }]). Test 2 never configures findContacts, yet it renders one list item. Why, and what is the fix?
Show answer
clearAllMocks only clears recorded calls. It keeps the configured resolved value, so test 2 still gets Test 1's data. Replace it with jest.resetAllMocks() in beforeEach, and set the value inside each test that needs it.
Exercise
Two tests each attach a component that uses the same test wire adapter, and the second test sees two rendered lists after one emit. What is missing from the file?
Show answer
The afterEach cleanup that removes elements from document.body. The first component is still connected, so the adapter delivers the emitted data to both components.