Sub topic 13
Testing components that use getRecord
This chapter assumes you can write a Lightning web component with @wire(getRecord) and updateRecord, as covered in earlier chapters. It also assumes you know basic Jest syntax (describe, it, expect) and async/await. You will write unit tests that run in Node with no org connection. The tests use @salesforce/sfdx-lwc-jest, the Jest setup for Lightning web components.
Why wires need special handling in tests
Unit tests run outside Salesforce, so there is no Lightning Data Service, no cache and no server. A component that wires getRecord would never receive data in that environment. sfdx-lwc-jest fixes this by replacing lightning/uiRecordApi with stubs. In current versions of the package, each wire adapter in the stub (such as getRecord) is a test adapter with three methods:
emit(value)pushes a result to every component wired to the adapter.error()pushes an error result instead.getLastConfig()returns the configuration the adapter last received, with reactive$values already resolved.
Imperative functions such as updateRecord and getRecordNotifyChange are different. They are plain functions, so you replace them with jest.fn() mocks.
The test controls the data, so you can check each branch of the component: data, error, and no result yet.
Setting up
Install the package in your SFDX project and run the tests:
npm install --save-dev @salesforce/sfdx-lwc-jest
npx sfdx-lwc-jestPlace test files in a __tests__ folder inside the component's folder, for example force-app/main/default/lwc/accountSummary/__tests__/accountSummary.test.js.
Schema imports such as @salesforce/schema/Account.Name also resolve under Jest. The Jest transformer turns them into reference objects, so you do not mock them.
Shaping the mock record
getFieldValue and getFieldDisplayValue read from a specific structure. Your mock data must use the same structure, or the getters return undefined and the test fails for the wrong reason. Each entry under fields holds a value and a displayValue.
const mockAccount = {
apiName: 'Account',
id: '001000000000001AAA',
fields: {
Name: { value: 'Acme', displayValue: null },
Industry: { value: 'Technology', displayValue: 'Technology' }
}
};Keep mock records like this in a JSON file next to the test if several tests share them. Only include fields the component reads.
Testing the data and error branches
This test targets the AccountSummary component from earlier in the tutorial. It covers three cases: data arrives, an error arrives, and the wire config receives the resolved record ID.
import { createElement } from 'lwc';
import AccountSummary from 'c/accountSummary';
import { getRecord } from 'lightning/uiRecordApi';
const mockAccount = {
apiName: 'Account',
id: '001000000000001AAA',
fields: {
Name: { value: 'Acme', displayValue: null },
Industry: { value: 'Technology', displayValue: 'Technology' }
}
};
const flushPromises = () => Promise.resolve();
function createComponent() {
const element = createElement('c-account-summary', { is: AccountSummary });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
return element;
}
describe('c-account-summary', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('passes the resolved recordId to the wire', () => {
createComponent();
expect(getRecord.getLastConfig().recordId).toBe('001000000000001AAA');
});
it('renders name and industry when data arrives', async () => {
const element = createComponent();
getRecord.emit(mockAccount);
await flushPromises();
const paragraphs = element.shadowRoot.querySelectorAll('p');
expect(paragraphs).toHaveLength(2);
expect(paragraphs[0].textContent).toBe('Name: Acme');
expect(paragraphs[1].textContent).toBe('Industry: Technology');
});
it('shows the error message when the wire errors', async () => {
const element = createComponent();
getRecord.error();
await flushPromises();
const paragraphs = element.shadowRoot.querySelectorAll('p');
expect(paragraphs).toHaveLength(1);
expect(paragraphs[0].textContent).toBe('The record could not be loaded.');
});
});Three details in this test matter.
- Rendering is asynchronous. After
emit()orerror(), the DOM does not update until the next microtask.await Promise.resolve()waits for that update. If your assertion runs before the wait, it sees the old DOM. - Clean up the DOM after each test. The stub adapters keep a list of connected components. A component left in
document.bodyfrom an earlier test receives lateremit()calls and can cause confusing failures. - Check the empty state too. Before any
emit(), the template renders nothing. A test that creates the element and asserts there are nopelements covers the loading state.
Testing a function-wired component
For a component like AccountNameLogger, where the wire target is a function, the same emit() and error() calls trigger the function. The function stores results in plain fields, so a test needs something observable. Either render those fields in the template and assert on the DOM, or keep the logic in a helper module and unit test it directly. Do not reach into the component instance, because createElement returns only the public surface.
Testing updateRecord
updateRecord is an ordinary imported function, so you mock the whole call. Replace only that export and keep the rest of the real stub:
jest.mock('lightning/uiRecordApi', () => ({
...jest.requireActual('lightning/uiRecordApi'),
updateRecord: jest.fn()
}));For this test, AccountRename needs a template. The spine shows only its JavaScript, so here is a minimal one:
<template>
<lightning-input label="New name" onchange={handleChange}></lightning-input>
<lightning-button label="Save" onclick={handleSave}></lightning-button>
</template>The test below checks the arguments passed to updateRecord and both toast outcomes.
import { createElement } from 'lwc';
import AccountRename from 'c/accountRename';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
jest.mock('lightning/uiRecordApi', () => ({
...jest.requireActual('lightning/uiRecordApi'),
updateRecord: jest.fn()
}));
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
async function renameTo(element, name) {
const input = element.shadowRoot.querySelector('lightning-input');
input.value = name;
input.dispatchEvent(new CustomEvent('change'));
element.shadowRoot.querySelector('lightning-button').click();
await flushPromises();
}
describe('c-account-rename', () => {
let element;
let toastHandler;
beforeEach(() => {
element = createElement('c-account-rename', { is: AccountRename });
element.recordId = '001000000000001AAA';
toastHandler = jest.fn();
element.addEventListener(ShowToastEvent.EventName, toastHandler);
document.body.appendChild(element);
});
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('sends Id and Name and shows a success toast', async () => {
updateRecord.mockResolvedValue({});
await renameTo(element, 'Globex');
expect(updateRecord).toHaveBeenCalledWith({
fields: { Id: '001000000000001AAA', Name: 'Globex' }
});
expect(toastHandler.mock.calls[0][0].detail.variant).toBe('success');
});
it('shows an error toast when the update is rejected', async () => {
updateRecord.mockRejectedValue({ body: { message: 'Validation failed' } });
await renameTo(element, 'Globex');
const detail = toastHandler.mock.calls[0][0].detail;
expect(detail.variant).toBe('error');
expect(detail.message).toBe('Validation failed');
});
});The rejection value mimics the shape the component reads, error.body.message. Real Lightning Data Service errors have that shape, so your mock should too.
The flushPromises helper here uses setTimeout. The component awaits updateRecord and then dispatches the event, which takes more than one microtask. A timer lets the whole chain finish.
Testing getRecordNotifyChange
The same pattern applies to AccountScore. Mock the Apex method and getRecordNotifyChange, trigger the handler, and assert on the calls. Apex imports do not exist in Jest, so mock them as virtual modules:
jest.mock(
'@salesforce/apex/AccountController.recalculateScore',
() => ({ default: jest.fn() }),
{ virtual: true }
);
jest.mock('lightning/uiRecordApi', () => ({
...jest.requireActual('lightning/uiRecordApi'),
getRecordNotifyChange: jest.fn()
}));After the handler runs, assert that getRecordNotifyChange was called with [{ recordId: '001000000000001AAA' }]. Also assert that it ran after the Apex mock resolved. A good second test makes the Apex mock reject and confirms the notify call does not happen.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion sees an empty DOM after `emit()` | No wait for the re-render | `await Promise.resolve()` before asserting |
| Getter returns `undefined` with data present | Mock record lacks `fields.X.value` | Match the real record shape |
| A test sees data from the previous test | Elements not removed from `document.body` | Clean up in `afterEach` |
| `getLastConfig().recordId` is `undefined` | Config read before `recordId` was set, or element not yet appended | Set the property, then `appendChild`, then read |
| `updateRecord` is not a mock function | `jest.mock` factory missing or placed after the import in a way Babel does not hoist | Keep `jest.mock` at module top level |
| Error toast test passes with no message | Mock rejection missing `body.message` | Reject with the shape the component reads |
What these tests do not prove
A unit test with mocked wires verifies your component's logic: how it handles data, errors and user actions. It does not verify that the fields you requested exist, that the user has field-level access, or that the cache refreshes after a server-side change. Cover those with a scratch org or sandbox check.
Exercise
A test creates the component, calls getRecord.emit(mockAccount), and immediately asserts that a paragraph with the account name exists. The assertion fails, but the same assertion passes after adding one line. What line is missing, and why does it fix the test?
Show answer
Add await Promise.resolve() (or a flushPromises helper) between emit() and the assertion. The component re-renders asynchronously after the wire provisions new data, so the DOM is not updated until a microtask has run. Awaiting a resolved promise lets that re-render finish before the assertion runs.
Exercise
Why do you mock updateRecord with jest.fn() while you drive getRecord with emit()?
Show answer
getRecord is a wire adapter, and the sfdx-lwc-jest stub turns it into a test adapter that can push values (emit, error) to wired components. updateRecord is an imperative function that returns a promise, so it has no emit. You replace it with a mock and set its result with mockResolvedValue or mockRejectedValue, then assert on the arguments it received.