Sub topic 13
Testing components that use getRecord
This chapter assumes you know Jest basics (describe, it, expect), the AccountSummary component from earlier chapters, and async/await. You will test that component without a Salesforce org.
Why wires need a test double
A wire adapter normally calls Lightning Data Service, which needs a connected org. Jest tests run in Node, so the adapter has to be replaced. The @salesforce/sfdx-lwc-jest package does this for you. It stubs lightning/uiRecordApi so that getRecord becomes a test wire adapter with these helpers:
emit(data)sends a result to every component wired to it.error()sends an error result.getLastConfig()returns the last configuration the adapter received.
Your test controls what the wire provides, so you can check each branch of the template.
Shape the mock data
getFieldValue and getFieldDisplayValue read from a record object with a fields map. Each field holds a value and a displayValue. Your mock must use the same shape, or the getters return undefined.
Write the tests
import { createElement } from 'lwc';
import AccountSummary from 'c/accountSummary';
import { getRecord } from 'lightning/uiRecordApi';
const RECORD_ID = '001000000000001AAA';
const mockAccount = {
apiName: 'Account',
id: RECORD_ID,
fields: {
Name: { value: 'Acme', displayValue: null },
Industry: { value: 'Energy', displayValue: 'Energy' }
}
};
function createComponent() {
const element = createElement('c-account-summary', {
is: AccountSummary
});
element.recordId = RECORD_ID;
document.body.appendChild(element);
return element;
}
describe('c-account-summary', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('passes the record id to the wire', async () => {
createComponent();
await Promise.resolve();
expect(getRecord.getLastConfig()).toEqual(
expect.objectContaining({ recordId: RECORD_ID })
);
});
it('renders the name and industry', async () => {
const element = createComponent();
getRecord.emit(mockAccount);
await Promise.resolve();
const paragraphs = element.shadowRoot.querySelectorAll('p');
expect(paragraphs[0].textContent).toBe('Name: Acme');
expect(paragraphs[1].textContent).toBe('Industry: Energy');
});
it('shows a message when the wire reports an error', async () => {
const element = createComponent();
getRecord.error();
await Promise.resolve();
const paragraph = element.shadowRoot.querySelector('p');
expect(paragraph.textContent).toBe('The record could not be loaded.');
});
});What each test proves
- The first test confirms the reactive parameter.
$recordIdresolves to the value set on the element, so the adapter receives the real ID instead of the literal string. - The second test confirms the data path. The component renders only after
emitprovidesaccount.data. - The third test confirms the error path. The
lwc:if={account.error}block appears only aftererror().
Common errors
- Forgetting to await. The DOM updates asynchronously. Without
await Promise.resolve(), assertions run against the old DOM and fail. - Skipping cleanup. Elements left in
document.bodyleak into later tests. TheafterEachabove prevents that. - Mock data in the wrong shape. A flat object such as
{ Name: 'Acme' }renders nothing. UsefieldswithvalueanddisplayValue. - Emitting before the element is connected. Append the element first. Only a connected component is subscribed to the adapter.
Exercise
A test emits a mock record to a component wired with getRecord, but the rendered text is blank. The mock is { Name: 'Acme' }. What is wrong, and how do you fix it?
Show answer
getFieldValue reads data.fields.Name.value, so a flat object yields undefined. Change the mock to { fields: { Name: { value: 'Acme', displayValue: null } } }. Also check that the test awaits Promise.resolve() after emit so the DOM has re-rendered.