Sub topic 14
Testing imperative calls with Jest
This chapter assumes you can write a basic LWC, you know how async/await and Promises behave, and you have a Salesforce DX project with @salesforce/sfdx-lwc-jest installed. You will test the contactSearch component from earlier chapters without touching a real org.
Why mock the Apex call
Jest runs in Node, not in Salesforce. There is no server, no session, and no Apex class. When your component imports @salesforce/apex/ContactController.searchContacts, Jest has nothing to resolve. You replace that import with a mock function that you control.
This gives you three benefits:
- Tests run in milliseconds and need no org.
- You choose exactly what the "server" returns, including failures.
- You can assert on the arguments your component sent.
You are testing the component's behavior. The Apex method itself is tested separately with Apex tests.
The test, step by step
This is the test from the plan. Read it first, then see the notes below.
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');
});
});Mocking the import
jest.mock replaces the module at that path. The factory returns an object with a default property, because the Apex import is a default export. jest.fn() is a mock function that records every call.
The { virtual: true } option tells Jest the module does not exist on disk. Without it, Jest throws "Cannot find module". The sfdx-lwc-jest resolver already stubs some @salesforce imports, but declaring the mock yourself gives you a function you can configure per test.
Setting the return value
mockResolvedValue(data) makes the mock return a Promise that resolves with data. This is the same shape the real imperative call produces, so await searchContacts(...) in the component works unchanged.
For failures, use mockRejectedValue. You will do this below.
Creating and attaching the element
createElement builds the component, and appendChild connects it to the DOM, which runs connectedCallback and renders the template. Query the rendered output through element.shadowRoot, because LWC uses shadow DOM.
Waiting for the Promise
Clicking the button starts handleSearch, which awaits the mock. The component updates only after the Promise settles and the re-render completes. flushPromises schedules a macrotask with setTimeout. Every pending microtask (Promise callback) runs before it, so by the time await flushPromises() returns, the component has processed the result and re-rendered.
Cleanup
The afterEach block removes elements so one test does not see another's DOM. jest.clearAllMocks() resets call history, so toHaveBeenCalledWith and toHaveBeenCalledTimes assertions stay accurate.
Test the error path
The success test covers one branch. The component also has an error branch that sets errorMessage and empties contacts. Test it with a rejected Promise.
An Apex error reaches the component as an object with a body.message property. Your mock should reproduce that shape.
it('shows an error message when Apex fails', async () => {
searchContacts.mockRejectedValue({
body: { message: 'Insufficient permissions' }
});
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
const errorEl = element.shadowRoot.querySelector('.slds-text-color_error');
expect(errorEl).not.toBeNull();
expect(errorEl.textContent).toBe('Insufficient permissions');
expect(element.shadowRoot.textContent).not.toContain('Ada Lovelace');
});Add this inside the same describe block. The error shape matters. If you reject with new Error('x'), the component falls back to error.message, which is a different branch of error?.body?.message || error?.message. Test both shapes if you want full branch coverage.
Test the loading state
The spinner shows while the Promise is pending. To observe it, control when the Promise resolves.
it('shows a spinner while the call is pending', async () => {
let resolveCall;
searchContacts.mockReturnValue(
new Promise((resolve) => {
resolveCall = 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();
resolveCall([]);
await flushPromises();
expect(element.shadowRoot.querySelector('lightning-spinner')).toBeNull();
});The Promise stays pending until you call resolveCall. The await Promise.resolve() gives the framework one microtask turn to re-render with isLoading set to true. After resolving, the finally block sets isLoading to false, and the spinner disappears.
Test the parameters
Your component should send the typed search term, not just the default empty string. Set the input value and fire its change event before the click.
it('sends the typed term to Apex', async () => {
searchContacts.mockResolvedValue([]);
const element = createElement('c-contact-search', { is: ContactSearch });
document.body.appendChild(element);
const input = element.shadowRoot.querySelector('lightning-input');
input.value = 'Ada';
input.dispatchEvent(new CustomEvent('change'));
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
expect(searchContacts).toHaveBeenCalledTimes(1);
expect(searchContacts).toHaveBeenCalledWith({ searchTerm: 'Ada' });
});The handler reads event.target.value. Because the event is dispatched on the input element, event.target is that element and holds 'Ada'. toHaveBeenCalledWith compares the argument deeply, so it verifies the object keys. A misspelled parameter name such as { term: 'Ada' } would fail here, and in production that mistake would send null to Apex with no error in the browser.
How the pieces fit
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module '@salesforce/apex/...'` | Missing `virtual: true` | Add `{ virtual: true }` to `jest.mock` |
| `searchContacts.mockResolvedValue is not a function` | The factory did not return `{ default: jest.fn() }` | Return an object with a `default` property |
| Assertion on rendered text fails, but no error | The test did not wait for the Promise | Add `await flushPromises()` before asserting |
| Calls from an earlier test appear in assertions | Mock history was not reset | Call `jest.clearAllMocks()` in `afterEach` |
| Error test passes but shows a generic message | Rejected with a plain `Error` instead of `{ body: { message } }` | Match the shape Apex errors have |
| Spinner assertion never sees the spinner | The mock resolved immediately | Use a manually controlled Promise |
Running the tests
Add a script to package.json if your project does not have one, then run it.
npm run test:unitA typical script entry is "test:unit": "sfdx-lwc-jest". Use sfdx-lwc-jest -- --watch while developing, and sfdx-lwc-jest -- --coverage to see which branches the tests leave untested. If the catch branch shows as uncovered, you are missing the error test above.
What not to test here
- Do not assert on SOQL, sharing, or
WITH USER_MODE. Those belong to Apex tests, because Jest never runs Apex. - Do not test that
lightning-cardrenders a title. Base components are stubs in Jest. - Do not rely on Jest to prove the real parameter names match the Apex signature. A mock accepts anything. Verify that against the org, or keep the parameter names covered by an Apex test and a deployment check.
Exercise
Your component calls updateEmail({ contactId: this.recordId, email: this.email }) imperatively and sets this.errorMessage = error.body.message on failure. Write the mock setup lines for a test that checks the error display, and name the one extra step the test needs after clicking the save button before it asserts on the rendered message.
Show answer
Mock the Apex import with jest.mock('@salesforce/apex/ContactController.updateEmail', () => ({ default: jest.fn() }), { virtual: true }), import it, then call updateEmail.mockRejectedValue({ body: { message: 'Invalid email' } }) before clicking. After the click, run await flushPromises() so the rejected Promise is handled and the component re-renders. Then assert that the rendered text contains Invalid email.
Exercise
A test asserts expect(searchContacts).toHaveBeenCalledTimes(1) and passes alone, but fails when the whole file runs. What is the most likely cause, and what is the fix?
Show answer
Call history from an earlier test is still recorded on the shared mock function. Add jest.clearAllMocks() to an afterEach block so each test starts with zero calls.