Sub topic 14
Testing imperative calls with Jest
This chapter assumes you can write a basic LWC, call an Apex method imperatively, and run sfdx-lwc-jest in a project. Jest tests run in Node, not in a Salesforce org. The @salesforce/apex/... import doesn't exist there, so you have to replace it with a mock.
How the mock works
A test for an imperative call has four parts:
- Replace the Apex import with a
jest.fn()usingjest.mockand{ virtual: true }. - Tell the mock what to return (
mockResolvedValue) or what error to throw (mockRejectedValue). - Trigger the user action, such as clicking the button.
- Wait for the Promise to settle and the DOM to re-render, then assert.
A passing test
This test mocks searchContacts from the earlier chapters and checks both the call and the result.
import { createElement } from 'lwc';
import ContactSearch from 'c/contactSearch';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
jest.mock(
'@salesforce/apex/ContactController.searchContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-search', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('renders contacts returned by Apex', async () => {
searchContacts.mockResolvedValue([
{ Id: '003000000000001', Name: 'Ada Lovelace', Email: '[email protected]' }
]);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(searchContacts).toHaveBeenCalledWith({ searchTerm: '' });
expect(element.shadowRoot.textContent).toContain('Ada Lovelace');
});
});Some details matter here:
virtual: truelets Jest mock a module path that doesn't exist on disk.- The factory returns
{ default: jest.fn() }because the component uses a default import. flushPromiseswaits one timer tick. By then the awaited Apex Promise has resolved and the component has re-rendered.toHaveBeenCalledWith({ searchTerm: '' })checks that parameters were passed as an object keyed by parameter name. The term is empty because the test never types into the input.afterEachremoves the component and clears mock call history, so tests don't affect each other.
Testing the error path
Error handling is where imperative calls most often break, so test it too. Apex errors reach the component as an object with a body.message property. The mock should reject with the same shape.
it('shows an error message when Apex fails', async () => {
searchContacts.mockRejectedValue({ body: { message: 'Insufficient access' } });
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(element.shadowRoot.textContent).toContain('Insufficient access');
expect(element.shadowRoot.querySelector('lightning-spinner')).toBeNull();
});The second assertion confirms that the finally block cleared the loading state. Without it, a failed call could leave the spinner on screen forever and the test would still pass on the message alone.
Common errors
| Symptom | Likely cause |
|---|---|
| `Cannot find module '@salesforce/apex/...'` | The `jest.mock` call is missing `{ virtual: true }`, or the path doesn't match the import. |
| `searchContacts.mockResolvedValue is not a function` | The factory didn't return `{ default: jest.fn() }`. |
| Assertion fails on rendered text | The test didn't wait. Add `await flushPromises()` after the click. |
| A test passes alone but fails with others | Mock state leaked. Call `jest.clearAllMocks()` in `afterEach`. |
| Rejected mock shows "Unknown error" | The rejection value lacks the `body.message` shape the component reads. |
Exercise
A test clicks the Search button, then immediately asserts that the list contains "Ada Lovelace". The assertion fails, although mockResolvedValue was set up correctly. What is missing, and why?
Show answer
The test must wait for the Promise to settle and the component to re-render, for example with await flushPromises() after the click. The click handler is async. The mock's Promise resolves in a microtask, so the DOM has not updated when the assertion runs synchronously after the click.
Exercise
Write the one line you would add to a test so that the mocked Apex method fails with the message "Record locked", in the shape the component reads.
Show answer
searchContacts.mockRejectedValue({ body: { message: 'Record locked' } });