Sub topic 2
Driving a Component with Test Wire Adapters
Assume you know LWC templates, @wire, Apex imports, Jest, and JavaScript promises. A test wire adapter lets a Jest test send controlled data or errors to a wired component without using a Salesforce org.
Driving a Component with Test Wire Adapters
Create and attach the component before emitting data. Flush pending promises before checking the DOM.
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));
it('renders contacts from the wire', 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();
expect(element.shadowRoot.querySelectorAll('li')).toHaveLength(2);
});emit supplies a successful value. Call getContactList.error() to test the error path.
flowchart TD
A[Test attaches component] --> B[Test wire adapter emits data]
B --> C[Component rerenders]
C --> D[Test checks shadow DOM]Mocking Built-In Adapters Such as `getRecord`
Salesforce data services, such as getRecord, also provide test adapters through sfdx-lwc-jest.
import { getRecord } from 'lightning/uiRecordApi';
const record = {
apiName: 'Account',
id: '001000000000001AAA',
fields: { Name: { value: 'Acme', displayValue: null } }
};
getRecord.emit(record);
await flushPromises();
expect(element.shadowRoot.querySelector('p').textContent).toBe('Acme');Set reactive properties, such as recordId, before attaching the component so the wire receives its configuration.
Mocking Wired and Imperative Apex
A wired Apex import uses createApexTestWireAdapter. An imperative Apex import uses jest.fn, which lets you control the promise:
import findContacts from '@salesforce/apex/ContactController.findContacts';
jest.mock(
'@salesforce/apex/ContactController.findContacts',
() => ({ default: jest.fn() }),
{ virtual: true }
);
findContacts.mockResolvedValue([{ Id: '001', Name: 'Amy Taylor' }]);
expect(findContacts).not.toHaveBeenCalled();After the component action, assert both the result and input:
expect(findContacts).toHaveBeenCalledWith({ searchTerm: 'Amy' });Use mockRejectedValue({ body: { message: 'Server error' } }) to test an Apex failure.
Exercise
Which method tests a wired Apex error?
Show answer
Call the mocked wire adapter's error() method, flush pending promises, and assert the error UI.