Sub topic 11
Test wired components
This chapter assumes you can write a basic Jest test for a Lightning web component (LWC). You should know createElement, shadow DOM queries, and how to wait for re-rendering. You should also know what @wire does. Earlier chapters covered those topics.
How wire testing differs
In a real org, the Lightning Data Service or Apex supplies wired data. In a Jest test there is no org. The @salesforce/sfdx-lwc-jest package therefore provides test wire adapters. A test wire adapter replaces the real adapter, and your test controls what it emits.
The flow is:
- Your test imports the adapter and calls its
emit()method with sample data. - The wired property or function in the component receives that data.
- The component re-renders.
- Your test waits one microtask and asserts on the DOM.
Wire an Apex method
Assume a c-contact-wire component that wires an Apex method. Its template shows each contact name, and it shows an error message if the wire returns an error.
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactWire extends LightningElement {
@wire(getContacts)
contacts;
}<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:if={contacts.error}>
<p class="error">Could not load contacts</p>
</template>
</template>To test it, import the Apex method with { createApexTestWireAdapter } from @salesforce/sfdx-lwc-jest and mock the module. The mock must be virtual, because the Apex class does not exist in your local project as a JavaScript module.
import { createElement } from 'lwc';
import { createApexTestWireAdapter } from '@salesforce/sfdx-lwc-jest';
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 }
);
describe('c-contact-wire', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders contacts when the wire emits data', async () => {
const element = createElement('c-contact-wire', { is: ContactWire });
document.body.appendChild(element);
getContacts.emit([{ Id: '003000000000001AAA', Name: 'Ada Lovelace' }]);
await Promise.resolve();
const items = element.shadowRoot.querySelectorAll('li');
expect(items).toHaveLength(1);
expect(items[0].textContent).toBe('Ada Lovelace');
});
it('shows an error message when the wire emits an error', 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('li')).toHaveLength(0);
});
});Notice that the factory function calls require inside the mock. Jest hoists jest.mock calls above the imports, so the factory cannot use variables imported at the top of the file. The unused top-level createApexTestWireAdapter import in the example is therefore not needed, and you can drop it.
Wire a platform adapter
Adapters such as getRecord from lightning/uiRecordApi work the same way. The test wire adapters for these are already registered by sfdx-lwc-jest, so you import the adapter and call emit() on it directly.
import { getRecord } from 'lightning/uiRecordApi';
getRecord.emit({ fields: { Name: { value: 'Acme' } } });The emitted object must match the shape the real adapter returns. If your component reads data.fields.Name.value, the sample data needs that same structure.
Common errors
| Symptom | Likely cause |
|---|---|
| `emit is not a function` | The module was mocked with a plain `jest.fn()` instead of a test wire adapter. |
| The DOM does not change after `emit()` | The test asserts before re-rendering. Add `await Promise.resolve()`. |
| Data from one test appears in the next | The element was not removed, or the adapter still holds the previous value. Clean up in `afterEach`. |
| Component reads `undefined` fields | The emitted data does not match the real response shape. |
Exercise
A test for a wired component calls getContacts.emit(data) and then immediately asserts on the rendered list, but the list is empty. What is missing, and why does it fix the problem?
Show answer
The test needs await Promise.resolve(); between emit() and the assertion. Emitting data updates the wired property, but LWC re-renders asynchronously in a microtask. Awaiting a resolved promise lets that re-render finish before the assertion reads the DOM.