Sub topic 10
Mock imperative Apex calls
An imperative Apex call is a call to an Apex method from JavaScript, made when your code decides to make it, such as in connectedCallback or a click handler. Jest tests run in Node.js without a Salesforce org, so there is no Apex to call. You replace the Apex import with a controllable fake. This chapter shows how to do that and how to test both the success path and the error path.
This chapter assumes you can already create a component with createElement, query its shadow root, and wait for re-rendering. It also assumes you are comfortable with promises and async/await.
What you are replacing
A component imports an Apex method like this:
import getContacts from '@salesforce/apex/ContactController.getContacts';At runtime, getContacts is a function that returns a promise. The promise resolves with the data the Apex method returned, or rejects with an error object. In Jest, no ContactController class exists. You replace the import with a jest.fn(), a mock function that records how it was called and returns whatever you tell it to.
The flow in a test looks like this:
The order matters. You configure the mock before you attach the component, because connectedCallback runs as soon as the element enters the document.
The component under test
The examples use a c-contact-list component. It loads contacts for an account when it is attached and shows either the names or an error message.
<template>
<template lwc:if={error}>
<p class="error">{error}</p>
</template>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.Id} class="contact">{contact.Name}</li>
</template>
</ul>
</template>import { LightningElement, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api accountId;
contacts = [];
error;
connectedCallback() {
getContacts({ accountId: this.accountId })
.then((result) => {
this.contacts = result;
})
.catch((e) => {
this.error = e.body.message;
});
}
}The e.body.message shape matches the errors that Lightning Web Components give you for a failed Apex call. Your mock should reject with the same shape, so the test exercises the same code path as production.
Declare the mock with jest.mock
Call jest.mock with the module path, a factory function that returns the fake module, and the option { virtual: true }.
jest.mock(
'@salesforce/apex/ContactController.getContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);Each part has a purpose:
- The first argument is the exact string used in the component's import. A typo means the real import is not replaced.
- The factory returns an object with a
defaultproperty, because the Apex import is a default export. virtual: truetells Jest that the module does not exist on disk. Without it, Jest tries to resolve the path and fails.
Then import the method in the test file the normal way. Thanks to the mock, you get the jest.fn() back:
import getContacts from '@salesforce/apex/ContactController.getContacts';Babel hoists jest.mock calls above the imports when the test runs, so the mock is in place before the component loads. For the same reason, the factory cannot use variables declared elsewhere in the file, unless their names start with mock. Creating jest.fn() inside the factory avoids the problem.
Test the success path
Set the return value with mockResolvedValue, create and attach the component, wait for the pending promises, and then assert.
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 }
);
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' },
{ Id: '003000000000002AAA', Name: 'Grace Hopper' }
]);
const element = createElement('c-contact-list', { is: ContactList });
element.accountId = '001000000000001AAA';
document.body.appendChild(element);
await flushPromises();
const names = Array.from(
element.shadowRoot.querySelectorAll('.contact')
).map((li) => li.textContent);
expect(getContacts).toHaveBeenCalledTimes(1);
expect(getContacts).toHaveBeenCalledWith({
accountId: '001000000000001AAA'
});
expect(names).toEqual(['Ada Lovelace', 'Grace Hopper']);
});
});Two assertions deserve attention. toHaveBeenCalledWith checks the parameters the component sent to Apex, which is where many real bugs hide, such as a misspelled parameter name. The names array checks the rendered output rather than a single textContent match, so a missing or duplicated row fails the test.
Test the error path
Use mockRejectedValue with an object shaped like the platform's error. Add this test inside the same describe block:
it('shows the error message when the Apex call fails', async () => {
getContacts.mockRejectedValue({
body: { message: 'You do not have access to these contacts.' }
});
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await flushPromises();
const error = element.shadowRoot.querySelector('.error');
expect(error).not.toBeNull();
expect(error.textContent).toBe(
'You do not have access to these contacts.'
);
expect(element.shadowRoot.querySelectorAll('.contact')).toHaveLength(0);
});Testing both paths matters because the error branch rarely runs during manual testing. A mock lets you trigger it on demand.
Why flushPromises instead of Promise.resolve
In the chapter on re-rendering, one await Promise.resolve() was enough, because the only pending work was a single render. Here the component has a promise chain: the Apex promise resolves, then .then or .catch runs, and then the re-render is queued. That takes several microtask turns, and one await Promise.resolve() might not cover them.
flushPromises schedules a setTimeout callback. Timers run only after the microtask queue is empty, so by the time your test continues, every chained promise has settled and the component has re-rendered. Use it whenever the component's code has a .then, .catch, or await between the trigger and the DOM change.
Isolate tests from each other
Mock functions keep their state between tests in the same file. Two cleanup functions matter:
| Function | Clears call history | Removes configured return values |
|---|---|---|
| `jest.clearAllMocks()` | Yes | No |
| `jest.resetAllMocks()` | Yes | Yes |
With only clearAllMocks, a value set by mockResolvedValue in one test is still active in the next. This is why each test above sets its own return value before creating the component. If you prefer a clean slate, call resetAllMocks in afterEach instead.
Common mistakes
- Forgetting to configure the mock. A bare
jest.fn()returnsundefined. The component then runsundefined.then(...)and throws aTypeErrorduringconnectedCallback. If you see that error, set a return value beforeappendChild. - Configuring the mock after attaching.
connectedCallbackhas already called the function and receivedundefined. - Omitting
virtual: true. Jest reports that it cannot find the module. - Rejecting with a plain
Error. A real failure hasbody.message. A mock that rejects withnew Error('x')makese.bodyundefined, and the component's catch block itself throws. - Asserting too early. A passing
toHaveBeenCalledTimes(1)followed by an empty DOM usually means the test did not wait for the promise chain.
Calls that happen on user action
The same technique applies to Apex calls triggered by a click. Configure the mock, create the component, click the element, then call await flushPromises() and assert. The only difference is that the call count is 0 until the click, so you can also assert expect(getContacts).not.toHaveBeenCalled() before interacting.
Exercises
Exercise
A test attaches a component whose connectedCallback calls an imported Apex method. The test fails with "TypeError: Cannot read properties of undefined (reading 'then')". The mock was declared with jest.mock(..., () => ({ default: jest.fn() }), { virtual: true }). What is the most likely cause and the fix?
Show answer
The mock function has no return value, so it returns undefined and the component calls .then on it. Fix it by calling getContacts.mockResolvedValue(...) (or mockRejectedValue) in the test before document.body.appendChild(element).
Exercise
Write the line that makes the mocked getContacts fail with a message of "Server unavailable", using the error shape the contactList component reads. Then name the helper you need to await before asserting that the message appears.
Show answer
getContacts.mockRejectedValue({ body: { message: 'Server unavailable' } }); followed by await flushPromises();, where flushPromises is () => new Promise((resolve) => setTimeout(resolve, 0)).