Sub topic 13
Common pitfalls and debugging
This chapter assumes you know basic LWC, @wire, importing Apex, Jest's describe, it, expect and jest.fn, and async/await. It collects the mistakes that most often break tests for wired and Apex-driven components, and shows how to find each one.
Pitfall 1: Missing `virtual: true`
Apex imports such as @salesforce/apex/ContactController.getContactList are not real files. Jest cannot resolve them unless the mock declares them as virtual.
jest.mock(
'@salesforce/apex/ContactController.findContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);Without the third argument, Jest fails with Cannot find module '@salesforce/apex/...'. If you see that message, check the options object first.
Pitfall 2: Asserting before rendering finishes
The DOM updates asynchronously. If you assert right after emit() or after a click, the template still shows the old state.
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
getContactList.emit([{ Id: '001', Name: 'Amy Taylor' }]);
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);Two symptoms point to this problem. An assertion sees an empty list that should hold data. Or a test passes alone but fails when the code around it changes. A single await Promise.resolve() is enough after a simple emit(). Use flushPromises when a mocked Apex promise has to resolve and then re-render.
Pitfall 3: Emitting before the component is connected
A wire adapter only delivers data to components that are in the DOM. Call document.body.appendChild(element) before emit() or error(). If you emit first, the component never receives the value.
Pitfall 4: Leaking state between tests
Components left in document.body and mock call history carry over to the next test. Use an afterEach that removes the elements and clears the mocks.
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});A typical symptom is toHaveBeenCalledWith passing for the wrong reason, because an earlier test made the same call. Another is querySelector finding an element from a previous test.
Pitfall 5: Using the wrong mock type
Wired Apex and imperative Apex need different mocks.
| Component code | Mock to use | How the test controls it |
|---|---|---|
| `@wire(getContactList)` | `createApexTestWireAdapter(jest.fn())` | `emit(data)`, `error()` |
| `findContacts({ ... }).then(...)` | `jest.fn()` | `mockResolvedValue`, `mockRejectedValue` |
| `@wire(getRecord, ...)` | Stub from `sfdx-lwc-jest` | `getRecord.emit(record)` |
If you call emit on a plain jest.fn(), you get emit is not a function. If you mock an imperative method with a wire adapter, the call never returns a promise and .then throws.
Pitfall 6: Forgetting the rejected shape
Components often read error.body.message. A test that rejects with a plain string passes the mock but crashes the component's error handler. Reject with the same shape Apex returns:
findContacts.mockRejectedValue({ body: { message: 'Server error' } });A debugging routine
When a test fails and the reason is unclear, work through these steps in order.
- Read the first error line.
Cannot find modulemeans a missing virtual mock.is not a functionmeans the wrong mock type. - Print the rendered output. Add
console.log(element.shadowRoot.innerHTML)afterawait flushPromises()to see what the component actually produced. - Confirm the order: append, emit or click, flush, assert.
- Check that the mock path string exactly matches the component's import, including class and method names.
- Run the single test with
npx jest path/to/file.test.js -t "test name". If it passes alone, the problem is leaked state from another test.
Exercise
A test calls getContactList.emit([...]) and then immediately checks that two li elements exist, but the check finds none. The mock uses createApexTestWireAdapter and the component is attached. What is the most likely cause and the fix?
Show answer
The test asserts before the component re-renders, because DOM updates are asynchronous. Add await flushPromises() (or await Promise.resolve()) after emit() and before the assertion.
Exercise
Jest reports Cannot find module '@salesforce/apex/ContactController.findContacts' when it runs your test. What do you change?
Show answer
Pass { virtual: true } as the third argument to jest.mock for that path, because Apex imports are not real modules on disk.