Sub topic 13
Unit testing wired components with Jest
This chapter assumes you have finished the earlier chapters. It also assumes you know basic Jest (describe, it, expect) and have a Salesforce DX project with @salesforce/sfdx-lwc-jest installed. You will test the ContactList component, which wires getContacts to a property.
Why wired components need a mock
Jest runs in Node, not in Salesforce. There is no Apex there, so @salesforce/apex/ContactController.getContacts cannot resolve to a real method. Your tests replace the import with a test wire adapter. The adapter lets the test push data or an error into the component, just as the platform would.
Mocking the Apex import
Declare the mock with jest.mock and the virtual: true option. The option is needed because the module does not exist on disk. Inside the factory, use createApexTestWireAdapter from @salesforce/sfdx-lwc-jest.
import { createElement } from 'lwc';
import ContactList from 'c/contactList';
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: '003000000000001', Name: 'Ada Lovelace' },
{ Id: '003000000000002', Name: 'Grace Hopper' }
];
describe('c-contact-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
function createComponent() {
const element = createElement('c-contact-list', { is: ContactList });
element.recordId = '001000000000001';
document.body.appendChild(element);
return element;
}
it('renders one item per contact', async () => {
const element = createComponent();
getContacts.emit(MOCK_CONTACTS);
await Promise.resolve();
const items = element.shadowRoot.querySelectorAll('li');
expect(items).toHaveLength(2);
expect(items[0].textContent).toBe('Ada Lovelace');
});
it('shows a message when the wire returns an error', async () => {
const element = createComponent();
getContacts.error();
await Promise.resolve();
const message = element.shadowRoot.querySelector('p');
expect(message.textContent).toBe('Could not load contacts.');
expect(element.shadowRoot.querySelector('ul')).toBeNull();
});
it('passes recordId as the wire parameter', () => {
createComponent();
expect(getContacts.getLastConfig()).toEqual({ accountId: '001000000000001' });
});
});What each part does
createElementbuilds the component. It is not rendered until you append it todocument.body.- Set
@apiproperties before you append the element. The wire readsrecordIdwhen the component connects, so the config is correct on the first call. emit(data)sends data to every component wired to that adapter. The component then receives{ data, error: undefined }.error()sends an error. The component receives{ data: undefined, error }, which is the branch your template renders.getLastConfig()returns the parameters the wire last used. It is how you check a$recordIdreactive parameter without a server.await Promise.resolve()waits one microtask. Rendering after a data change is asynchronous, so queries made before it see the old DOM.- The
afterEachcleanup keeps one test's DOM from leaking into the next.
Testing a function wire
If a component wires to a function, as in ContactListFn, the same adapter drives it. emit and error call your function with { data } or { error }. Assert on the fields your function sets, such as rows or errorMessage. Test them through the rendered DOM, not by reading private fields.
For refreshApex, mock the @salesforce/apex module so you can assert it was called with the stored wire result.
jest.mock(
'@salesforce/apex',
() => ({ refreshApex: jest.fn(() => Promise.resolve()) }),
{ virtual: true }
);Running the tests
Run the suite with npx sfdx-lwc-jest or an npm script that wraps it. Add -- --watch while you write tests. A component that is wired but also calls Apex imperatively needs a different mock. Use a plain jest.fn() for the default export and call mockResolvedValue or mockRejectedValue on it.
Exercise
In a Jest test for a component that wires getContacts with { accountId: '$recordId' }, how do you verify that the wire used the right record Id, and why must you set recordId before appending the element?
Show answer
Call getContacts.getLastConfig() and compare it with { accountId: '<the Id>' }. The wire reads the $recordId value when the component connects to the DOM. Setting recordId first means the first wire config already holds the Id. If you set it after appending, the first config has accountId undefined and the test sees an extra update.