Sub topic 13
Common pitfalls and debugging
This chapter lists the mistakes that most often break LWC Jest tests for wired and imperative Apex components. Each section gives the symptom, the cause, and the fix. It ends with a routine for finding the cause of a failing test.
It assumes you have read the earlier chapters. You should know how to create a component with createElement, how test wire adapters use emit and error, and how jest.fn mocks an imperative Apex call. You should also be comfortable with async/await.
Pitfall 1: Forgetting `virtual: true`
An Apex import such as @salesforce/apex/ContactController.getContactList is not a file on disk. Jest cannot resolve it, so jest.mock fails unless you mark the mock as virtual.
Symptom: the test suite fails before any test runs, with an error like Cannot find module '@salesforce/apex/ContactController.getContactList' from 'contactList.test.js'.
jest.mock(
'@salesforce/apex/ContactController.findContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);The third argument, { virtual: true }, tells Jest that the module does not exist on disk and the factory should be used instead. Add it to every mock of an Apex import. Mocks for lightning/uiRecordApi and similar modules do not need it, because sfdx-lwc-jest already ships stubs for them.
Two related mistakes give the same kind of failure:
- A typo in the module path. The path in
jest.mockmust match the component's import character for character, including the class and method names. - Mocking
defaultincorrectly. The factory must return an object with adefaultkey, as in{ default: jest.fn() }. Returning a barejest.fn()makes the importundefined.
Pitfall 2: Asserting before the DOM updates
LWC renders asynchronously. When a wire emits data or a mocked promise resolves, the component's properties change right away, but the template re-renders in a later microtask. An assertion written on the next line sees the old DOM.
Symptom: expect(items.length).toBe(2) fails with Received: 0, although the same component works in an org.
getContactList.emit([{ Id: '001', Name: 'Amy Taylor' }]);
// Wrong: the template has not re-rendered yet.
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
// Right: wait for pending promises first.
await flushPromises();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);How many ticks you need depends on the path:
| Situation | Enough to wait |
|---|---|
| A wire `emit` followed by a render | `await Promise.resolve()` |
| An imperative call (`mockResolvedValue`, then `.then`, then render) | `await flushPromises()` |
| A click handler that awaits an Apex call and then sets state | `await flushPromises()` |
When unsure, use flushPromises. It defers to a setTimeout callback, which runs after all queued microtasks. One caveat: if the test uses jest.useFakeTimers(), setTimeout(resolve, 0) never fires on its own, and the test times out. Either avoid fake timers in tests that need flushPromises, or advance the timers explicitly.
Tests that pass without checking anything
A related mistake is forgetting async on the test function, or forgetting await on flushPromises(). The test body then finishes before the assertions run. Jest reports a pass, and any later failure is lost or surfaces in an unrelated test.
// Wrong: the assertion runs after the test has already passed.
it('renders contacts', () => {
getContactList.emit([{ Id: '001', Name: 'Amy Taylor' }]);
flushPromises().then(() => {
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
});
});Make the test async, and await every promise inside it. If you want a safety net, call expect.assertions(n) at the top of the test. Jest then fails the test if fewer than n assertions ran.
Pitfall 3: Emitting before the component is connected
A wire adapter instance is created when the component connects to the DOM. If you call emit before document.body.appendChild(element), no adapter is listening yet, and the data is lost.
Symptom: the component stays in its loading state, and emit raises no error.
Always append the element first, then emit:
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element); // connects the component, creates the wire
getContactList.emit([{ Id: '001', Name: 'Amy Taylor' }]);
await flushPromises();Pitfall 4: Mock state leaking between tests
Test adapters and jest.fn() mocks live at module level, so they survive from one test to the next. Two kinds of leak are common.
First, elements left in the DOM. An earlier test's component stays attached and may still react to emitted data. Remove every child of document.body in afterEach, as in the earlier chapters.
Second, mock implementations that persist. jest.clearAllMocks() clears recorded calls but keeps implementations. If one test calls findContacts.mockRejectedValue(...), a later test that forgets to set a value still gets the rejection.
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.resetAllMocks();
});jest.resetAllMocks() clears calls and also removes implementations, so every test starts with a bare jest.fn() that returns undefined. The consequence is that each test must set its own mockResolvedValue or mockRejectedValue. A component that does findContacts(...).then(...) on an undefined return throws Cannot read properties of undefined (reading 'then'). That error means your test forgot to configure the mock.
Pitfall 5: Mock factory scope errors
jest.mock calls are hoisted to the top of the file, above your imports and variables. A factory function therefore cannot use variables defined elsewhere in the file. Jest rejects such references with a message that says "The module factory of jest.mock() is not allowed to reference any out-of-scope variables."
This is why the wire mock requires the helper inside the factory:
jest.mock(
'@salesforce/apex/ContactController.getContactList',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);Calling require inside the factory works because it runs when the factory runs. An import at the top of the file would not be available yet. Variables whose names start with mock, such as mockData, are exempt from the check, but they are still hoisted above, so they must be initialized before the component first uses the mock.
Pitfall 6: Wrong error shape
Components usually read error.body.message. If a test rejects with new Error('Server error'), error.body is undefined, and the component throws inside its own error handler.
Mimic the shape Apex returns:
findContacts.mockRejectedValue({ body: { message: 'Server error' } });For wires, getContactList.error() emits a default error object. Use it for tests that only check that the error UI appears. If the component displays the message text, pass an error object with the same body.message shape the component reads.
Pitfall 7: Querying the wrong tree
Components use synthetic shadow DOM, so document.querySelector does not reach inside a component. Query from element.shadowRoot. Content that a child component renders is inside that child's own shadow root. From the parent test you can find the child element, but you can't see its inner markup. Assert on the child's public properties instead, or test the child on its own.
Base components such as lightning-input are replaced by stubs in sfdx-lwc-jest. The stub has the public properties, but it does not render the real input. This is why the earlier example sets input.value and dispatches a change event by hand.
Debugging routine
When a test fails and the cause is not obvious, work through these steps in order.
- Read the first line of the error. Module resolution errors point to Pitfall 1. A
.thenofundefinedpoints to a reset mock (Pitfall 4). - Print what the component rendered. This shows the real state of the DOM:
``javascript console.log(element.shadowRoot.innerHTML); ``
- Check whether the mock ran. Call
expect(findContacts).toHaveBeenCalled()as the first assertion. If it fails, the problem is in how the test triggers the component, not in the mock. - Run the test alone. Use
npx jest contactSearch.test.js -t "shows an error". If it passes alone but fails in the full suite, state is leaking from another test. - For wire config problems, inspect the config the component passed. The test adapters from sfdx-lwc-jest provide
getLastConfig(), which returns the most recent config the wire received. Use it when a reactive parameter such as$recordIdseems to have the wrong value.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module '@salesforce/apex/...'` | Missing `virtual: true` or a path typo | Add the option and match the import path exactly |
| Import is `undefined` | Factory did not return `{ default: ... }` | Return an object with a `default` key |
| Assertion sees the old DOM | Promises not flushed | `await flushPromises()` |
| Test passes but checks nothing | Missing `async` or `await` | Make the test `async` and use `expect.assertions` |
| Component stays in loading state | `emit` before `appendChild` | Append, then emit |
| `.then` of `undefined` | Mock reset and not reconfigured | Set `mockResolvedValue` in each test |
| Error text is empty | Rejected value lacks `body.message` | Reject with `{ body: { message } }` |
| Passes alone, fails in suite | Leaked DOM or mock state | Clean up in `afterEach` |
Exercise
A test mocks findContacts with jest.fn() and calls findContacts.mockResolvedValue([{ Id: '001', Name: 'Amy Taylor' }]). The afterEach hook calls jest.resetAllMocks(). The first test passes, but a second test that does not set a return value fails with "Cannot read properties of undefined (reading 'then')". Why, and what are two ways to fix it?
Show answer
resetAllMocks removes the mock's implementation, so the second test's findContacts returns undefined, and the component calls .then on it. Fix it by setting mockResolvedValue (or mockRejectedValue) inside every test that triggers the call, or by using jest.clearAllMocks in afterEach and setting a fresh value at the start of each test. Setting the value in a beforeEach also works.
Exercise
A wired component test calls getContactList.emit([...]) and then immediately asserts that two li elements exist. The assertion fails with 0 items. The element is appended to the document before the emit. What is missing, and why?
Show answer
The test must wait for the re-render with await flushPromises() (or await Promise.resolve() for a plain wire emit) before asserting. The emit updates the component's data right away, but LWC re-renders the template in a later microtask, so the DOM is still unchanged on the next line. The test function must also be async.