Sub topic 9
Mocking imperative Apex calls
This chapter assumes you can write a basic Jest test, that you know how to import an Apex method into a Lightning Web Component, and that you are comfortable with async/await. You should also have a test that creates a component with createElement and waits for rendering, as covered in the earlier chapters.
What "imperative" means for testing
A wired Apex method is called by the platform, and a test adapter pushes data to it. An imperative Apex method is different because your component calls it. The imported name is a plain function that returns a promise, and your code decides when to call it, usually in a click handler or in connectedCallback.
This changes what you need from a mock in three ways:
- The mock must be callable and must return a promise.
- The test must control whether that promise resolves or rejects.
- The test can check how the component called it, including the arguments.
Jest's jest.fn() provides all three. You do not need createApexTestWireAdapter here. That helper is for @wire and does not apply to direct calls.
The component under test
The examples in this chapter use a small search component. It calls findContacts when the user clicks the button. It tracks a loading flag, a list of results, and an error.
import { LightningElement } from 'lwc';
import findContacts from '@salesforce/apex/ContactController.findContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
error;
isLoading = false;
handleChange(event) {
this.searchTerm = event.target.value;
}
async handleSearch() {
this.isLoading = true;
try {
this.contacts = await findContacts({ searchTerm: this.searchTerm });
this.error = undefined;
} catch (e) {
this.error = e;
this.contacts = [];
} finally {
this.isLoading = false;
}
}
get errorMessage() {
return this.error && this.error.body ? this.error.body.message : 'Unknown error';
}
get isEmpty() {
return !this.isLoading && !this.error && this.contacts.length === 0;
}
}<template>
<lightning-input label="Name" onchange={handleChange}></lightning-input>
<lightning-button label="Search" onclick={handleSearch}></lightning-button>
<lightning-spinner lwc:if={isLoading} alternative-text="Loading"></lightning-spinner>
<p lwc:if={error} class="error">{errorMessage}</p>
<p lwc:if={isEmpty} class="empty">No contacts found.</p>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>Replacing the import with jest.fn
An Apex method such as ContactController.findContacts lives in the org, not on disk. Jest cannot load it from a file, so you replace the whole module with jest.mock and a factory function. Two details matter:
- The factory must return an object with a
defaultproperty, because the component uses a default import. - The third argument must be
{ virtual: true }. It tells Jest the module path does not need to exist on disk. Without it, the mock can fail with a "cannot find module" error.
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 }
);The test file imports findContacts normally. Because of the mock, the import gives you the jest.fn() that the component also receives. Jest hoists jest.mock calls above the imports, so the replacement is in place before the component loads.
Controlling the result
Set the behavior of the mock before the action that triggers the call. Jest provides two helpers for promise-returning functions:
| Helper | Equivalent to | Use it for |
|---|---|---|
| `mockResolvedValue(x)` | `mockImplementation(() => Promise.resolve(x))` | The success path |
| `mockRejectedValue(e)` | `mockImplementation(() => Promise.reject(e))` | The error path |
Both set the behavior for every later call until you reset it. Use mockResolvedValueOnce or mockRejectedValueOnce when only the next call should behave this way.
The success path
This test drives the component through its real interface. It sets the input value, fires change, and clicks the button.
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-search imperative Apex', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('calls Apex with the search term and shows results', async () => {
findContacts.mockResolvedValue([{ Id: '001', Name: 'Amy Taylor' }]);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
input.value = 'Amy';
input.dispatchEvent(new CustomEvent('change'));
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(findContacts).toHaveBeenCalledWith({ searchTerm: 'Amy' });
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
});
});The await flushPromises() line matters. After the click, the handler awaits the mocked promise. Then LWC re-renders in a later microtask. A setTimeout of zero lets all of that finish before your assertions run.
The error path
Real Apex errors reach the component as objects with a body.message property. Build your rejected value to match that shape, because the component reads error.body.message. If you reject with a plain string, you test a shape that production never sends.
it('shows an error when Apex rejects', async () => {
findContacts.mockRejectedValue({ body: { message: 'Server error' } });
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
const error = element.shadowRoot.querySelector('.error');
expect(error).not.toBeNull();
expect(error.textContent).toBe('Server error');
});Checking textContent is stronger than checking that the element exists. It proves the component reads the error from the shape you expect.
The empty path
An empty result is a success, not an error. Resolve with an empty array and check that the component shows its empty message and no list items.
it('shows the empty message when no contacts match', async () => {
findContacts.mockResolvedValue([]);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(element.shadowRoot.querySelector('.empty')).not.toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});Testing the loading state
Both helpers above settle immediately, so by the time you assert, the loading state is gone. To observe loading, return a promise that you resolve yourself. This is often called a deferred promise.
it('shows a spinner while the call is pending', async () => {
let resolveApex;
findContacts.mockReturnValue(
new Promise((resolve) => {
resolveApex = resolve;
})
);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('lightning-spinner')).not.toBeNull();
resolveApex([{ Id: '001', Name: 'Amy Taylor' }]);
await flushPromises();
expect(element.shadowRoot.querySelector('lightning-spinner')).toBeNull();
});A single await Promise.resolve() is enough for the first check. The click sets isLoading synchronously, and the re-render needs one microtask. Calling resolveApex later lets the handler continue.
Asserting what the component sent
A test that only checks rendered output can pass even when the component sends the wrong parameters, because the mock returns the same data regardless of its input. Use the mock's call record to close that gap:
toHaveBeenCalledWith({ searchTerm: 'Amy' })checks the arguments. Apex methods take a single object whose keys match the Apex parameter names, so check the key names too.toHaveBeenCalledTimes(1)catches handlers that fire twice.not.toHaveBeenCalled()proves that nothing was sent, for example when a required field is empty.findContacts.mock.calls[0][0]gives you the first argument when you need to inspect a part of it.
Keeping the mock isolated between tests
The mock function is created once per test file, so its state persists across tests. A value set in one test can leak into the next. Choose the cleanup method based on what you need:
| Call | Clears call history | Removes `mockResolvedValue` and other implementations |
|---|---|---|
| `jest.clearAllMocks()` | Yes | No |
| `jest.resetAllMocks()` | Yes | Yes |
With the bare jest.fn() used here, resetAllMocks is the safer choice if every test sets its own return value. If your factory gives the mock a default implementation, resetAllMocks removes it too, so set the default again in beforeEach. Keep the DOM cleanup in afterEach. Components left in document.body from earlier tests can still react to events and make later assertions confusing.
Common errors
- Missing
virtual: true. The test fails with a "cannot find module" error for the@salesforce/apex/...path. - Missing
defaultin the factory. The component receives an object instead of a function, and the call fails with "is not a function". - No value set on the mock. A bare
jest.fn()returnsundefined. Theawaitthen yieldsundefined, and the component may fail oncontacts.length. Always set a resolved or rejected value before triggering the call. - Assertions before the flush. The list is still empty or the spinner is still shown. Add
await flushPromises()before you assert. - Rejecting with the wrong shape. The test passes while production code fails on
error.body. Mirror the real error shape. - Mock name mismatch. The path in
jest.mockmust match the import path exactly, including the class and method names.
Exercise
A test sets findContacts.mockResolvedValue([{ Id: '001', Name: 'Amy Taylor' }]), clicks the button, and immediately checks querySelectorAll('li').length without awaiting anything. The check finds 0 items. Why, and what is the smallest fix?
Show answer
The component awaits the mocked promise, and LWC re-renders in a later microtask, so the list has not been updated yet when the assertion runs. Add await flushPromises() (or an equivalent wait) after the click and before the assertion.
Exercise
Write the lines that make findContacts fail with a realistic Apex error whose message is "No access", and then assert that the component called Apex exactly once.
Show answer
findContacts.mockRejectedValue({ body: { message: 'No access' } });
After the click and await flushPromises(), use expect(findContacts).toHaveBeenCalledTimes(1);
Exercise
Why might test B see the result that test A set up with mockResolvedValue, and which Jest call in afterEach stops it?
Show answer
The mock function is shared across all tests in the file, and mockResolvedValue sets a persistent implementation. jest.clearAllMocks() only clears call history, so the implementation survives. jest.resetAllMocks() also removes the implementation, so each test must set its own value.