Sub topic 11
Test wired components
This chapter assumes you can already create a component with createElement, query its shadow root, and wait one microtask before asserting. It also assumes you have mocked an imperative Apex call with a virtual jest.mock. If any of that is unfamiliar, review the earlier chapters first.
Why wired components need a different approach
A component that calls Apex imperatively controls when the call happens, so a test can resolve a mock promise and wait. A wired component does not. The wire service decides when to call the adapter and what to provide, and it provisions data to the component whenever the adapter has a value.
In a Jest test there is no wire service and no org. You replace the adapter with a test wire adapter. The test adapter lets you push data or an error into the component yourself, and it records the configuration the component sent to it.
The component under test
The following component wires an Apex method to a reactive parameter. The '$accountId' string tells the wire service to re-provision whenever the public accountId property changes.
<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id} class="contact">{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:if={contacts.error}>
<p class="error">Could not load contacts.</p>
</template>
</template>import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactWire extends LightningElement {
@api accountId;
@wire(getContacts, { accountId: '$accountId' })
contacts;
}The Apex method must be marked @AuraEnabled(cacheable=true) for @wire to accept it. Jest does not check this, so a mistake only appears when you deploy.
When a wire is applied to a property, the property holds an object with data and error keys. Before any value arrives, both are undefined. That is why the template can read contacts.data safely from the first render.
Register an Apex wire adapter
For an Apex method used with @wire, the mock must be a test wire adapter instead of a plain jest.fn(). The package provides createApexTestWireAdapter for this. Create it inside the jest.mock factory, because Jest hoists jest.mock calls above your imports and the factory cannot reference variables defined later in the file.
import { createElement } from 'lwc';
import ContactWire from 'c/contactWire';
import getContacts from '@salesforce/apex/ContactController.getContacts';
jest.mock(
'@salesforce/apex/ContactController.getContacts',
() => {
const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest');
return { default: createApexTestWireAdapter(jest.fn()) };
},
{ virtual: true }
);
const MOCK_CONTACTS = [
{ Id: '003000000000001AAA', Name: 'Ada Lovelace' },
{ Id: '003000000000002AAA', Name: 'Grace Hopper' }
];
describe('c-contact-wire', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('renders one item per contact when data is emitted', async () => {
const element = createElement('c-contact-wire', { is: ContactWire });
document.body.appendChild(element);
getContacts.emit(MOCK_CONTACTS);
await Promise.resolve();
const items = element.shadowRoot.querySelectorAll('.contact');
expect(items).toHaveLength(2);
expect(items[0].textContent).toBe('Ada Lovelace');
expect(element.shadowRoot.querySelector('.error')).toBeNull();
});
it('shows an error message when the wire fails', async () => {
const element = createElement('c-contact-wire', { is: ContactWire });
document.body.appendChild(element);
getContacts.error();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
expect(element.shadowRoot.querySelectorAll('.contact')).toHaveLength(0);
});
});Three points about this test:
- The imported
getContactsis the adapter. Because the module is mocked, the default import is the test adapter. It has the extra methodsemit,error, andgetLastConfig, which a real Apex method does not. emitpushes data. The component sees it as a successful wire result. The value should have the same shape the real Apex method returns, so use realistic records.errorpushes a failure. The component'scontacts.erroris populated andcontacts.dataisundefined. You can pass a body and status, such asgetContacts.error({ message: 'Boom' }, 500), if your component displays them.
Check the wire configuration
A wired component also has a contract with the adapter: the parameters it sends. getLastConfig returns the most recent configuration the component supplied. Use it to verify reactive parameters.
it('sends the accountId to the wire and updates it when changed', async () => {
const element = createElement('c-contact-wire', { is: ContactWire });
element.accountId = '001000000000001AAA';
document.body.appendChild(element);
await Promise.resolve();
expect(getContacts.getLastConfig()).toEqual({
accountId: '001000000000001AAA'
});
element.accountId = '001000000000002AAA';
await Promise.resolve();
expect(getContacts.getLastConfig()).toEqual({
accountId: '001000000000002AAA'
});
});Add this test inside the same describe block. It covers what a mocked imperative call cannot show: that the $accountId dependency is wired correctly, so a rename or typo in the config fails a test.
Wire adapters from Lightning Data Service
The lightning/ui*Api modules, such as getRecord from lightning/uiRecordApi, are replaced automatically by the sfdx-lwc-jest setup with test wire adapters. You do not call jest.mock for them. You import the adapter and call emit on it.
Assume a component c-account-name that wires getRecord with the Account.Name field and renders the value in an element with the class name:
import { createElement } from 'lwc';
import AccountName from 'c/accountName';
import { getRecord } from 'lightning/uiRecordApi';
const MOCK_RECORD = {
apiName: 'Account',
id: '001000000000001AAA',
fields: {
Name: { displayValue: null, value: 'Acme' }
}
};
describe('c-account-name', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders the record name', async () => {
const element = createElement('c-account-name', { is: AccountName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
getRecord.emit(MOCK_RECORD);
await Promise.resolve();
expect(element.shadowRoot.querySelector('.name').textContent).toBe('Acme');
});
});The emitted object must look like the real User Interface API response. If your component reads data.fields.Name.value, the mock needs that structure. Copying a real response into a JSON file under __tests__/data/ and loading it with require keeps the mock accurate.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `getContacts.emit is not a function` | The Apex module was mocked with `jest.fn()` instead of a test wire adapter | Return `createApexTestWireAdapter(jest.fn())` from the mock factory |
| `The module factory of jest.mock() is not allowed to reference any out-of-scope variables` | The factory uses an imported value | `require` the helper inside the factory, as shown above |
| Emitted data never appears | The test asserts before the re-render, or emits before the component is attached | Append the element first, then `emit`, then `await Promise.resolve()` |
| Component shows data from a previous test | The DOM or the mock state leaked between tests | Clean up `document.body` and call `jest.clearAllMocks()` in `afterEach` |
| Wrong shape renders nothing | The emitted value differs from the real response | Use a recorded real response as mock data |
What to cover for each wired component
- The loaded state: emit realistic data and assert on the rendered output.
- The empty state: emit an empty array or a record with missing fields.
- The error state: call
error()and assert on the message or fallback UI. - The wire configuration: assert on
getLastConfig()for every reactive parameter. - Reactivity: change the public property and assert the configuration changes.
Exercise
A test for a wired component calls getContacts.emit(MOCK_CONTACTS) and then immediately asserts that the list has two items. The assertion fails, although the same assertion passes if you add one line between the two statements. What is the line, and why is it needed?
Show answer
Add await Promise.resolve(); (and make the test function async). Emitting data updates the component's wired property, but LWC re-renders the template asynchronously in a microtask. Awaiting a resolved promise lets that re-render finish before the assertion reads the shadow DOM.
Exercise
You mock @salesforce/apex/ContactController.getContacts with () => ({ default: jest.fn() }) and call getContacts.emit([]) in a test for a component that uses @wire(getContacts). The test throws "emit is not a function". How do you fix the mock?
Show answer
Replace the plain jest.fn() with a test wire adapter. Inside the factory, run const { createApexTestWireAdapter } = require('@salesforce/sfdx-lwc-jest'); and return { default: createApexTestWireAdapter(jest.fn()) }, keeping { virtual: true } as the third argument of jest.mock.