Sub topic 8
Mocking wired Apex methods
This chapter covers how to test a component that gets data from a wired Apex method. It assumes you know basic Lightning Web Components (templates, decorators, lifecycle hooks), @wire and Apex imports, basic Jest (describe, it, expect, jest.fn), and promises with async/await. It also assumes you have already created a component with createElement and attached it to the DOM.
The problem to solve
A wired Apex method is an Apex method marked @AuraEnabled(cacheable=true) and connected to a component with @wire. In production, the platform provides the wire adapter and runs the Apex on the server. Jest has neither, so the import @salesforce/apex/ContactController.getContactList fails with "Cannot find module".
The fix is to replace the import with a test wire adapter. A test wire adapter is a fake adapter that your test controls. The test pushes data or an error into the component's wired property, and then checks what the component rendered. No server and no Apex code is involved.
The component under test
This component wires getContactList to a property named contacts. The property receives an object with data and error fields.
import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
export default class ContactList extends LightningElement {
@wire(getContactList) contacts;
get hasError() {
return Boolean(this.contacts && this.contacts.error);
}
get isEmpty() {
return Boolean(
this.contacts && this.contacts.data && this.contacts.data.length === 0
);
}
get items() {
return (this.contacts && this.contacts.data) || [];
}
}The template has three states: an error message, an empty message, and the list.
<template>
<template lwc:if={hasError}>
<p class="error">Could not load contacts.</p>
</template>
<template lwc:elseif={isEmpty}>
<p class="empty">No contacts found.</p>
</template>
<template lwc:else>
<ul>
<template for:each={items} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
</template>Replacing the import with createApexTestWireAdapter
The package @salesforce/sfdx-lwc-jest exports createApexTestWireAdapter. You pass it a jest.fn() and it returns a wire adapter that also has test controls: emit, error, and getLastConfig. You register it with jest.mock.
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
import getContactList from '@salesforce/apex/ContactController.getContactList';
jest.mock(
'@salesforce/apex/ContactController.getContactList',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);Three details in this block matter:
virtual: true. The module path@salesforce/apex/...does not exist on disk. Without this option, Jest looks for a real file and fails.requireinside the factory. Jest hoistsjest.mockcalls above the imports. The factory therefore cannot use variables from the file scope, so it requires the helper itself.defaultexport. An Apex import is a default import. The mock must return{ default: ... }, so thatimport getContactList from ...receives the adapter.
The imported getContactList in the test file is the same adapter object the component uses. That shared object is how the test reaches the component.
How a test drives the component
The order is important. The component has to be attached to the DOM before you call emit, because the adapter only delivers values to components that are connected. Rendering is asynchronous, so the test must wait before it reads the DOM.
Testing the success path
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('c-contact-list wired Apex', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders one item per contact', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
getContactList.emit([
{ Id: '001', Name: 'Amy Taylor' },
{ Id: '002', Name: 'Michael Jones' }
]);
await flushPromises();
const items = element.shadowRoot.querySelectorAll('li');
expect(items.length).toBe(2);
expect(items[0].textContent).toBe('Amy Taylor');
});
});emit takes the value the Apex method would return. Here that is an array of contact records. The component sees contacts.data set to that array and contacts.error set to undefined.
Testing the error path
Call error() to simulate a failed Apex call. The component then sees contacts.error set and contacts.data set to undefined.
it('renders an error message when the wire errors', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
getContactList.error();
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
expect(element.shadowRoot.querySelector('li')).toBeNull();
});The second assertion checks that no list is rendered. A test that only checks for the error message could still pass if the component showed both the message and stale data.
Testing the empty path
An empty array is a valid successful response. It is a different state from an error and from "not loaded yet", and components often handle it with its own message.
it('renders an empty message when Apex returns no contacts', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
getContactList.emit([]);
await flushPromises();
expect(element.shadowRoot.querySelector('.empty')).not.toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});Checking the wire configuration
Many wired Apex methods take parameters. The component declares them in a config object, and a $ prefix marks a reactive value that comes from a component property.
import { LightningElement, api, wire } from 'lwc';
import getContactsByAccount from '@salesforce/apex/ContactController.getContactsByAccount';
export default class AccountContacts extends LightningElement {
@api recordId;
@wire(getContactsByAccount, { accountId: '$recordId' })
contacts;
}The test adapter records the config it last received. getLastConfig() returns it, so you can confirm that the component sent the right parameters.
import { createElement } from 'lwc';
import AccountContacts from 'c/accountContacts';
import getContactsByAccount from '@salesforce/apex/ContactController.getContactsByAccount';
jest.mock(
'@salesforce/apex/ContactController.getContactsByAccount',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);
it('passes the record id to the wire config', async () => {
const element = createElement('c-account-contacts', { is: AccountContacts });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
await Promise.resolve();
expect(getContactsByAccount.getLastConfig()).toEqual({
accountId: '001000000000001AAA'
});
});If recordId were undefined, the wire would not provision data at all. For wired Apex, a reactive parameter that is undefined is treated as "not ready". The test above sets recordId before attaching the element, so the config is complete when the wire connects.
What the test adapter does not do
The test adapter does not run your Apex logic. It also does not check that the data you emit has the right shape. If you emit { Id: '001', Nme: 'Amy' }, the adapter accepts it, and the failure only appears in your assertions. Build emitted data from a fixture that matches the fields in your Apex query. A shared JSON file or a constant at the top of the test file keeps these shapes consistent.
Because the adapter also does not model caching or refresh, tests that depend on refreshApex need a different approach. That topic is outside this chapter.
Common mistakes with wired Apex mocks
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module '@salesforce/apex/...'` | `jest.mock` has no `{ virtual: true }` option | Add `{ virtual: true }` as the third argument |
| `emit is not a function` | The factory returned `jest.fn()` instead of the adapter, or forgot `default` | Return `{ default: createApexTestWireAdapter(jest.fn()) }` |
| `ReferenceError` inside the factory | The factory used a variable from the outer scope | Call `require('@salesforce/sfdx-lwc-jest')` inside the factory |
| The DOM is unchanged after `emit` | The test read the DOM before rendering finished | `await flushPromises()` before querying |
| Emitted data has no effect | The test called `emit` before `appendChild` | Attach the element first, then emit |
| One test sees the previous test's list | Elements from earlier tests are still in `document.body` | Remove all children in `afterEach` |
Exercises
Exercise
Your test file contains this mock and fails with "Cannot find module '@salesforce/apex/CaseController.getCases'". What is missing, and why? jest.mock('@salesforce/apex/CaseController.getCases', () => { const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest'); return { default: createApexTestWireAdapter(jest.fn()) }; });
Show answer
The third argument { virtual: true } is missing. The path @salesforce/apex/... does not exist as a file on disk. Without the virtual option, Jest tries to resolve it from the file system and fails. With { virtual: true }, Jest accepts the factory as the module without looking for a file.
Exercise
A component renders <p class="empty"> when contacts.data is an empty array. Write the body of a Jest test, after the element is created and attached, that checks this behavior with the test adapter getContactList. Name the two steps that must happen before the assertion.
Show answer
Emit an empty array, then wait for rendering, then assert:
getContactList.emit([]);
await flushPromises();
expect(element.shadowRoot.querySelector('.empty')).not.toBeNull();
The two steps before the assertion are calling emit([]) on the adapter and awaiting flushPromises() so the component can re-render.
Exercise
A component declares @wire(getContactsByAccount, { accountId: '$recordId' }). Which adapter method lets a test confirm the value of accountId that the component sent, and when should the test set recordId?
Show answer
getLastConfig() returns the config the adapter received last, for example { accountId: '001000000000001AAA' }. The test should set element.recordId before calling document.body.appendChild(element), so the config is complete when the wire connects.