Sub topic 6
Driving a component with test wire adapters
This chapter assumes you know basic Lightning Web Components (templates, decorators, lifecycle hooks), the @wire decorator, and Apex imports. It also assumes basic Jest (describe, it, expect, jest.fn) and promises with async/await. You should already know how to create a component with createElement and flush promises, which earlier chapters cover.
By the end you will be able to push data and errors into a wired property from a test and assert on what the component renders.
What a test wire adapter is
In production, a wire adapter is a function the platform connects to your component. When the component is added to the DOM, the adapter starts. It then provisions values to the wired property or function, and it provisions again whenever its inputs change.
In Jest there is no platform and no org. The @salesforce/sfdx-lwc-jest package therefore replaces adapters with test wire adapters. A test wire adapter does no work on its own. It waits for your test to tell it what to deliver. It has two methods you use most:
emit(value)delivers a value to every connected component that uses the adapter. The component sees it asdata.error(body, status, statusText)delivers an error. The component sees it aserror. All arguments are optional.
The adapter also remembers the configuration the component passed it. You read that back with getLastConfig(). A later chapter covers that. This chapter focuses on emit and error.
A component to test
The examples below use a small component that wires an Apex method to a property. Wiring to a property (not a function) gives you an object with data and error fields.
// contactList.js
import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
export default class ContactList extends LightningElement {
@wire(getContactList) contacts;
}<!-- contactList.html -->
<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:elseif={contacts.error}>
<p class="error">Could not load contacts.</p>
</template>
<template lwc:else>
<p class="loading">Loading...</p>
</template>
</template>The template has three branches, so a good test suite has at least three tests: loading, success, and error. The empty-list case is a fourth, and a later chapter covers it.
The setup that makes `emit` available
Wired Apex methods need a mock that swaps the import for a test adapter. This is the same setup you will see in the Apex chapters, repeated here because the tests depend on it.
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 }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));Three details matter here:
- The
virtual: trueoption is required because the Apex module does not exist on disk. Without it, Jest fails to resolve the path. - The
requirecall sits inside the factory.jest.mockcalls are hoisted above imports, so the factory cannot rely on variables declared elsewhere in the file. - After the mock, the imported
getContactListis the test adapter. That is whygetContactList.emit(...)works in the tests.
Test 1: the loading state
Before anything is emitted, the wired property has no data and no error. This is the state a user sees while the request is in flight.
describe('c-contact-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('shows the loading message before data arrives', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
await flushPromises();
expect(element.shadowRoot.querySelector('.loading')).not.toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});
});Do not skip this test. It proves the component does not crash when contacts.data is undefined, which is a common source of runtime errors in templates and getters.
Test 2: emitting data
Append the component first, then emit. Then wait for the rerender and assert.
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 runs synchronously, but the component's DOM does not change until the next rerender. Without the await, the assertion runs against the old DOM and finds zero li elements. Chapter errors of this kind look like a failing assertion with a "correct" component, so check for a missing await first.
Emit after appendChild. The adapter delivers values to connected instances, so a value emitted before the component is in the DOM has nobody to receive it.
Test 3: emitting an error
it('shows 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('.loading')).toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(0);
});Asserting that the other branches are absent is cheap and catches templates where two branches render at once. If your component displays text from the error, pass a body that matches what the real server sends, for example getContactList.error({ message: 'Server error' }), and assert on the rendered text.
What each call looks like to the component
| Test call | Wired property afterward | Typical template branch |
|---|---|---|
| Nothing yet | `data` and `error` both undefined | Loading |
| `emit(array)` | `data` is the array, `error` undefined | Success |
| `error(body)` | `error` is set, `data` undefined | Error |
| `emit(...)` after `error(...)` | `data` set, `error` cleared | Success again |
The last row is useful for testing recovery. A refresh after a failure should replace the error message with the list. You can test this by calling error(), flushing, then calling emit(...) and flushing again.
it('recovers from an error when new data arrives', async () => {
const element = createElement('c-contact-list', { is: ContactList });
document.body.appendChild(element);
getContactList.error();
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
getContactList.emit([{ Id: '001', Name: 'Amy Taylor' }]);
await flushPromises();
expect(element.shadowRoot.querySelector('.error')).toBeNull();
expect(element.shadowRoot.querySelectorAll('li').length).toBe(1);
});Built-in adapters use the same pattern
Adapters from lightning/uiRecordApi and similar modules already have test versions in sfdx-lwc-jest, so you do not need a jest.mock for them. You import the adapter and call emit on it. A later chapter covers these in detail. This short example shows how similar the flow is.
import { createElement } from 'lwc';
import RecordName from 'c/recordName';
import { getRecord } from 'lightning/uiRecordApi';
const mockRecord = {
apiName: 'Account',
id: '001000000000001AAA',
fields: { Name: { value: 'Acme', displayValue: null } }
};
it('shows the account name from getRecord', async () => {
const element = createElement('c-record-name', { is: RecordName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
getRecord.emit(mockRecord);
await Promise.resolve();
expect(element.shadowRoot.querySelector('p').textContent).toBe('Acme');
});Note the shape of mockRecord. It must look like the real record representation, with fields holding objects that have value and displayValue. A flat { Name: 'Acme' } would not match what the component reads from data.fields.Name.value.
Common mistakes with test wire adapters
- Emitting before the component is connected. Append the element, then emit.
- Forgetting to await after
emitorerror. The DOM updates asynchronously. - Mock data that does not match the real shape. The test passes, but production fails. Copy a real response when you can.
- Leaving elements in the DOM between tests. A component from a previous test stays connected and also receives the next
emit. Remove everything inafterEach, as in the examples above. - Using
jest.mockwithoutvirtual: truefor Apex. Jest reports that it cannot find the module.
Exercise
A test appends a wired component, calls getContactList.emit([{ Id: '001', Name: 'Amy Taylor' }]), and immediately asserts querySelectorAll('li').length is 1. The assertion fails with 0, though the component is correct. What is wrong, and what is the fix?
Show answer
The component rerenders asynchronously after emit, so the assertion runs against the DOM from before the new data was rendered. Add await flushPromises() (or at least await Promise.resolve()) between the emit call and the assertion, and make the test function async.
Exercise
Write a test sequence, in words, that verifies a component recovers after an error, and name the two assertions you would make at the end.
Show answer
Append the component, call error() on the adapter, and flush promises. Then call emit(...) with valid data and flush again. At the end, assert that the .error element is no longer in the shadow DOM, and that the expected number of li elements is rendered.