Sub topic 9
Mocking imperative Apex calls
This chapter assumes you know basic Lightning Web Components, can write Jest tests with describe, it, expect and jest.fn, and are comfortable with promises and async/await. It also assumes you have already created a component with createElement and flushed promises, as covered in earlier chapters.
What "imperative" means here
A wired Apex method runs when its parameters change. An imperative call runs when your code calls it, usually from a click handler. The import looks the same, but the component calls it like a function and gets a promise back.
import findContacts from '@salesforce/apex/ContactController.findContacts';
handleSearch() {
findContacts({ searchTerm: this.searchTerm })
.then((result) => { this.contacts = result; this.error = undefined; })
.catch((error) => { this.error = error; this.contacts = undefined; });
}In Jest there is no server beh import. You replace it with jest.fn(), so the test decides what the promise does.
Replace the import with jest.fn
Wired Apex needs a test wire adapter. Imperative Apex only needs a plain mock function.
jest.mock(
'@salesforce/apex/ContactController.findContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);Two details matter:
- The factory returns an object with a
defaultkey, because the component uses a default import. { virtual: true }tells Jest the module does not exist on disk. Without it, Jest fails with "Cannot find module".
How the call flows
The test never reaches Salesforce. It controls what the mock returns.
Test the success path
Set the return value before the component can call the method. Then trigger the action, flush promises, and assert.
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));
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);
});
});mockResolvedValue(data) is shorthand for a function that returns Promise.resolve(data). The await flushPromises() lets the .then handler run and the component re-render before the assertions.
Test the error path
Use mockRejectedValue to simulate a failed call. Apex errors reach the component as objects with a body.message property, so mock that shape.
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();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
});Add this it block inside the same describe.
Common mistakes
| Symptom | Likely cause |
|---|---|
| `Cannot find module '@salesforce/apex/...'` | Missing `{ virtual: true }` |
| `findContacts is not a function` | Factory returned the function directly instead of `{ default: ... }` |
| Assertion sees old DOM | Promises were not flushed before `expect` |
| Mock returns `undefined` and the component throws on `.then` | No `mockResolvedValue` or `mockRejectedValue` set for that test |
| A result from one test leaks into the next | `jest.clearAllMocks()` is missing in `afterEach` |
Exercise
A test calls findContacts.mockResolvedValue([...]), clicks the button, and immediately runs expect(element.shadowRoot.querySelectorAll('li').length).toBe(1). The assertion fails with 0. What is missing, and why?
Show answer
The test must await flushPromises() (or an equivalent) after the click. The mock returns a promise, so the .then handler that stores the result and triggers the re-render runs asynchronously. Without waiting, the assertion runs before the DOM updates.
Exercise
Which assertion confirms the component sent the right parameters to Apex, and why must the argument be wrapped in an object?
Show answer
expect(findContacts).toHaveBeenCalledWith({ searchTerm: 'Amy' });. Imperative Apex methods take a single object whose keys match the Apex parameter names, so the component passes { searchTerm: ... } and the assertion must match that shape.