Sub topic 10
Mock imperative Apex calls
This chapter assumes you can write a basic Jest test for a Lightning web component. That means using createElement, querying the shadow root, and waiting for re-rendering. It also assumes you are comfortable with promises and async/await.
Why mock Apex
An imperative Apex call is a function you import from @salesforce/apex/Class.method and call from JavaScript. It returns a promise. In a Jest run there is no org and no Apex class, so the import cannot resolve. You replace it with a Jest mock function. Then you decide what it returns and check how the component reacts.
Declare the mock
The component under test imports the Apex method. The test must declare a mock for the same module path before the component loads.
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
import getContacts from '@salesforce/apex/ContactController.getContacts';
jest.mock(
'@salesforce/apex/ContactController.getContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);Three details matter here:
- The factory returns an object with a
defaultkey, because the Apex import is a default export. virtual: truetells Jest the module does not exist on disk. Without it, Jest fails with "Cannot find module".- Jest hoists
jest.mockcalls above the imports, so the mock is in place whenc/contactListloads.
Resolve with sample data
Set the return value inside each test, so tests stay independent. mockResolvedValue makes the mock return a promise that resolves with the value you give it.
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('calls the Apex method and renders its result', async () => {
getContacts.mockResolvedValue([{ Id: '003000000000001AAA', Name: 'Ada Lovelace' }]);
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await flushPromises();
expect(getContacts).toHaveBeenCalledTimes(1);
expect(element.shadowRoot.textContent).toContain('Ada Lovelace');
});
});The test assumes c-contact-list calls getContacts when it loads and renders each contact name.
Why flushPromises
await Promise.resolve() waits one microtask. An Apex call involves a chain of promises: the mock resolves, the component's then or await continues, and then a re-render is scheduled. One microtask is often not enough. flushPromises uses setTimeout, which runs after all queued microtasks have finished. This gives the whole chain time to complete.
Test the error path
Use mockRejectedValue to simulate a failure. Real Apex errors arrive as objects with a body.message property, so shape your fake the same way.
it('shows an error when the Apex call fails', async () => {
getContacts.mockRejectedValue({ body: { message: 'Callout failed' } });
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await flushPromises();
expect(element.shadowRoot.textContent).toContain('Callout failed');
});Add this inside the same describe block. The exact text depends on how your component displays errors.
Check the arguments
A mock records its calls. For a method that takes parameters, check what the component sent.
expect(getContacts).toHaveBeenCalledWith({ accountId: '001000000000001AAA' });Imperative Apex takes a single object whose keys match the Apex parameter names.
Common errors
| Symptom | Likely cause |
|---|---|
| `Cannot find module '@salesforce/apex/...'` | `virtual: true` is missing from the `jest.mock` call. |
| `getContacts.mockResolvedValue is not a function` | The factory does not return `{ default: jest.fn() }`. |
| DOM is still empty at the assertion | You waited only one microtask. Use `flushPromises`. |
| A test sees data from an earlier test | You did not call `jest.clearAllMocks()` in `afterEach`. |
Exercise
Your test calls getContacts.mockResolvedValue(data), appends the component, and awaits Promise.resolve(). The assertion on the rendered names fails because the DOM is empty. What is the most likely cause, and how do you fix it?
Show answer
One microtask is not enough for the Apex promise chain and the following re-render to finish. Replace the wait with await flushPromises(), where flushPromises returns a promise resolved by setTimeout(resolve, 0).
Exercise
Write the line that makes the mocked getContacts simulate an Apex error with the message "No access".
Show answer
getContacts.mockRejectedValue({ body: { message: 'No access' } });