Sub topic 8
Mocking wired Apex methods
This chapter assumes you know how to create a component with createElement, how @wire delivers data to a component, and how to import an Apex method in LWC. It also assumes basic Jest (describe, it, expect, jest.fn) and async/await.
What you are replacing
A component can wire an Apex method like this:
import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
export default class ContactList extends LightningElement {
@wire(getContactList)
contacts;
}In Jest there is no org, so the @salesforce/apex/ContactController.getContactList module does not exist. Jest cannot resolve the import, and the test fails before it starts. You fix this by mocking the module and giving the component a test wire adapter in place of the real one.
The adapter comes from createApexTestWireAdapter, which @salesforce/sfdx-lwc-jest provides. It behaves like a wire adapter, but your test controls what it sends.
Write the mock
Call jest.mock with the exact module path of the Apex import. The factory returns an object whose default export is the test adapter.
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 matter here:
{ virtual: true }tells Jest the module has no file on disk. Without it, Jest throws "Cannot find module".requireis used inside the factory. Jest hoistsjest.mockcalls above imports, so the factory cannot rely on imports declared in the file.- The
getContactListyou import in the test is the mocked default export. It carries theemitanderrormethods.
Emit data
Create the component, attach it, then call emit with the data the Apex method would return. Wait for the DOM to update before you assert.
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);
});
});The component must be in the DOM before you call emit. A wire connects when the element is attached, so an emit sent earlier has nothing to receive it.
Emit an error
Call error() to simulate a failed Apex call. The wired property then receives an error instead of data.
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();
});Put this it inside the same describe as the data test. The assertion assumes your template shows an element with the class error when the wire returns an error.
Common mistakes
| Symptom | Likely cause |
|---|---|
| "Cannot find module '@salesforce/apex/...'" | The `jest.mock` call is missing `{ virtual: true }`, or the path differs from the import. |
| `emit is not a function` | The factory returned a plain `jest.fn()` instead of `createApexTestWireAdapter(jest.fn())`. |
| Assertions see the old DOM | The test did not wait for `flushPromises` after `emit` or `error`. |
| Data from one test appears in the next | The component was left in the DOM. Clean up in `afterEach`. |
Exercise
Your test calls getContactList.emit([...]) and then immediately runs querySelectorAll('li'), but the result is empty. Name the fix and explain why it works.
Show answer
Add await flushPromises() between the emit and the query. The component re-renders asynchronously after the wired property changes, so the DOM has not updated when the query runs. Waiting for pending promises lets the render finish first.
Exercise
A new test file mocks @salesforce/apex/AccountController.getAccounts with jest.mock(path, () => ({ default: createApexTestWireAdapter(jest.fn()) })) and Jest reports "Cannot find module". What two changes does the mock need?
Show answer
Add { virtual: true } as the third argument, and load createApexTestWireAdapter with require('@salesforce/sfdx-lwc-jest') inside the factory, because jest.mock is hoisted above the file's imports.