Sub topic 7
Mocking built-in adapters such as getRecord
This chapter assumes you can write a basic Jest test for an LWC. It also assumes you know what @wire does and how to create a component with createElement. You will test a component that reads a record through getRecord, and you will drive it with data and errors without an org.
Why built-in adapters need no hand-written mock
Apex methods are imports from @salesforce/apex/.... They only exist in your org, so you must mock them yourself. Built-in adapters such as getRecord from lightning/uiRecordApi are different. The @salesforce/sfdx-lwc-jest package already ships a stub for each lightning/* module. When your component imports lightning/uiRecordApi under Jest, it receives that stub, not the real module.
The stub of getRecord is a test wire adapter. It does not call a server. It gives your test three controls:
| Method | What it does |
|---|---|
| `getRecord.emit(data)` | Pushes data into every component wired to `getRecord`. The wired property receives `{ data, error: undefined }`. |
| `getRecord.error()` | Pushes an error. The wired property receives `{ data: undefined, error }`. |
| `getRecord.getLastConfig()` | Returns the last config object the component supplied, such as `{ recordId, fields }`. |
Your test imports getRecord from the same module as the component does. The test and the component then share one adapter instance.
The component under test
This component shows an account name. It uses a reactive $recordId in the wire config. It shows the name when data arrives and a message when the wire reports an error.
// recordName.js
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class RecordName extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
account;
get name() {
return this.account.data
? getFieldValue(this.account.data, NAME_FIELD)
: undefined;
}
}<!-- recordName.html -->
<template>
<template lwc:if={account.data}>
<p class="name">{name}</p>
</template>
<template lwc:if={account.error}>
<p class="error">Could not load the account.</p>
</template>
</template>The @salesforce/schema/Account.Name import also works under Jest. The sfdx-lwc-jest resolver turns it into an object with objectApiName and fieldApiName, so you do not mock it.
Building the mock record
The data you emit must look like what the real adapter returns. A record in the User Interface API shape has apiName, id, and a fields map. Each entry in fields has a value and a displayValue.
const mockRecord = {
apiName: 'Account',
id: '001000000000001AAA',
fields: {
Name: { value: 'Acme', displayValue: null }
}
};Include only the fields your component reads. Keep the field keys identical to the API names in your wire config, because getFieldValue looks them up by fieldApiName.
Many teams keep such records in a JSON file next to the test and import them. This keeps large payloads out of the test body.
Testing the success path
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 } }
};
describe('c-record-name with getRecord', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
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('.name').textContent).toBe('Acme');
expect(element.shadowRoot.querySelector('.error')).toBeNull();
});
});The order of the steps matters:
- Create the element and set its public properties.
- Append it to the DOM. This connects the wire.
- Call
emit. - Wait for the re-render, then assert.
A single await Promise.resolve() is enough here because one change schedules one render. If the component chains promises of its own, use the flushPromises helper from the earlier chapter instead.
Testing the error path
Call error() instead of emit(). The component then receives an error object in account.error.
it('shows an error message when getRecord fails', async () => {
const element = createElement('c-record-name', { is: RecordName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
getRecord.error();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.error')).not.toBeNull();
expect(element.shadowRoot.querySelector('.name')).toBeNull();
});Put this test in the same describe block as the success test. Each test creates its own element, so the two do not interfere as long as afterEach removes the element.
Testing the loading state
Before any emit or error call, the wired property has neither data nor error. You can test that state by not calling either method.
it('renders nothing before the wire responds', async () => {
const element = createElement('c-record-name', { is: RecordName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
await Promise.resolve();
expect(element.shadowRoot.querySelector('.name')).toBeNull();
expect(element.shadowRoot.querySelector('.error')).toBeNull();
});This test is cheap and catches templates that assume data always exists.
Checking the wire config
The component supplies a config to the adapter. With $recordId, the config changes whenever recordId changes. Use getLastConfig() to confirm the component sends what you expect.
it('passes the record id to getRecord', async () => {
const element = createElement('c-record-name', { is: RecordName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
await Promise.resolve();
expect(getRecord.getLastConfig().recordId).toBe('001000000000001AAA');
});
it('updates the config when recordId changes', async () => {
const element = createElement('c-record-name', { is: RecordName });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
await Promise.resolve();
element.recordId = '001000000000002AAA';
await Promise.resolve();
expect(getRecord.getLastConfig().recordId).toBe('001000000000002AAA');
});Assert on specific properties of the config, not the whole object. The fields array contains the schema object, and comparing it adds noise to the test without adding confidence.
Other built-in adapters follow the same pattern
Any lightning/* wire adapter that sfdx-lwc-jest stubs works the same way. You import it from its module, call emit or error, and read getLastConfig. The data you emit must match the shape the real adapter returns.
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
getObjectInfo.emit({
apiName: 'Account',
fields: { Name: { label: 'Account Name', dataType: 'String' } }
});Check which adapters the installed version of sfdx-lwc-jest stubs. Look in node_modules/@salesforce/sfdx-lwc-jest/src/lightning-stubs. If your component imports a module that has no stub, Jest fails to resolve it. You then supply your own mock with jest.mock, as in the next section.
Imperative functions from the same module
getRecord is a wire adapter, but lightning/uiRecordApi also exports functions you call yourself, such as updateRecord. These return promises, so a wire adapter's emit does not apply. Replace the function with jest.fn while keeping the rest of the module.
import { updateRecord } from 'lightning/uiRecordApi';
jest.mock('lightning/uiRecordApi', () => {
const actual = jest.requireActual('lightning/uiRecordApi');
return { ...actual, updateRecord: jest.fn() };
});
it('saves the record', async () => {
updateRecord.mockResolvedValue({ id: '001000000000001AAA' });
// create the component, trigger the save, await, then assert
// expect(updateRecord).toHaveBeenCalled();
});jest.requireActual returns the sfdx-lwc-jest stub for the module, so getRecord and getFieldValue keep working. After this jest.mock call, updateRecord.mockResolvedValue and mockRejectedValue control the outcome the same way they do for imperative Apex.
Common mistakes with built-in adapters
- Emitting before the component connects. The data goes nowhere. Append the element first.
- Emitting a record without the fields the component reads.
getFieldValuereturnsundefined, and the text is empty. Compare your mock with the fields in the wire config. - Forgetting to clean up. A component left in
document.bodystays connected, so a lateremitalso updates it. This produces confusing results in the next test. - Using the real module path in
jest.mock. You rarely needjest.mockforgetRecordat all. Only add it for functions the stub does not provide. - Expecting
error()to throw. It delivers the error to the wired property. The component decides how to show it.
Exercise
A test creates the c-record-name component, calls getRecord.emit(mockRecord), and only then calls document.body.appendChild(element). The test fails because the name is missing. What is the cause, and how do you fix it?
Show answer
The test wire adapter only delivers data to components that are already connected, so emit reached no component. Append the element to the document first, then call getRecord.emit(mockRecord), then await a promise and assert on the rendered output.
Exercise
Write the assertion that checks the component sent the record Id 001000000000003AAA to getRecord after the test sets element.recordId to that value and attaches the element.
Show answer
After awaiting Promise.resolve(), assert expect(getRecord.getLastConfig().recordId).toBe('001000000000003AAA'). The getLastConfig method returns the config the component last supplied to the adapter.