Sub topic 14
Testing with Jest and Avoiding Common Pitfalls
This chapter assumes you have built the updateDescription screen action and the notifyRecord headless action from earlier chapters. It also assumes you know the basics of Jest (describe, it, expect) and have a Salesforce DX project with Node.js installed. Here you will write unit tests for both actions and learn the mistakes that most often break quick actions in an org.
What Jest can and cannot test
Jest runs your component in Node.js, not in Salesforce. It checks your component's logic: what it renders, what it calls, and which events it dispatches. It cannot check anything the platform does around your component.
| Concern | Checked by Jest | Checked in an org |
|---|---|---|
| `handleSave` calls `updateRecord` with the right fields | Yes | Yes |
| Toast and close events are dispatched | Yes | Yes |
| `js-meta.xml` target and `actionType` are valid | No | Yes |
| Action appears on the page layout | No | Yes |
| `recordId` is supplied by the platform | Only if you set it | Yes |
| Field-level security and validation rules | No | Yes |
Setting up sfdx-lwc-jest
The sfdx-lwc-jest package provides the Jest configuration and stubs for lightning/* modules and base components.
npm install @salesforce/sfdx-lwc-jest --save-dev
npx sfdx-lwc-jest -- --watchAll=falsePut tests in a __tests__ folder inside the component bundle, for example force-app/main/default/lwc/updateDescription/__tests__/updateDescription.test.js.
Testing the screen action
The screen action depends on three platform modules. You replace updateRecord with a Jest mock so you control success and failure. You replace CloseActionScreenEvent with a plain CustomEvent that has the same event type, so the test can listen for it. The toast needs no mock, because the stub for lightning/platformShowToastEvent fires a lightning__showtoast event with your parameters in detail.
The component dispatches events on its host element, and they do not bubble. Attach listeners to the element you created.
import { createElement } from 'lwc';
import UpdateDescription from 'c/updateDescription';
import { updateRecord } from 'lightning/uiRecordApi';
jest.mock('lightning/uiRecordApi', () => ({ updateRecord: jest.fn() }), { virtual: true });
jest.mock('lightning/actions', () => ({
CloseActionScreenEvent: class extends CustomEvent {
constructor() {
super('lightning__actionsclosescreen');
}
}
}), { virtual: true });
const RECORD_ID = '001000000000001AAA';
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
function setup() {
const element = createElement('c-update-description', { is: UpdateDescription });
element.recordId = RECORD_ID;
document.body.appendChild(element);
const onClose = jest.fn();
const onToast = jest.fn();
element.addEventListener('lightning__actionsclosescreen', onClose);
element.addEventListener('lightning__showtoast', onToast);
return { element, onClose, onToast };
}
function typeDescription(element, text) {
const textarea = element.shadowRoot.querySelector('lightning-textarea');
textarea.value = text;
textarea.dispatchEvent(new CustomEvent('change'));
}
function clickButton(element, label) {
element.shadowRoot.querySelector(`lightning-button[label="${label}"]`).click();
}
describe('c-update-description', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('saves the description, shows a success toast, and closes', async () => {
updateRecord.mockResolvedValue({});
const { element, onClose, onToast } = setup();
typeDescription(element, 'New text');
clickButton(element, 'Save');
await flushPromises();
expect(updateRecord).toHaveBeenCalledWith({
fields: { Id: RECORD_ID, Description: 'New text' }
});
expect(onToast.mock.calls[0][0].detail.variant).toBe('success');
expect(onClose).toHaveBeenCalledTimes(1);
});
it('shows an error toast and stays open when the save fails', async () => {
updateRecord.mockRejectedValue({ body: { message: 'Validation failed' } });
const { element, onClose, onToast } = setup();
typeDescription(element, 'Bad text');
clickButton(element, 'Save');
await flushPromises();
const detail = onToast.mock.calls[0][0].detail;
expect(detail.variant).toBe('error');
expect(detail.message).toBe('Validation failed');
expect(onClose).not.toHaveBeenCalled();
});
it('closes without saving when Cancel is clicked', () => {
const { element, onClose } = setup();
clickButton(element, 'Cancel');
expect(updateRecord).not.toHaveBeenCalled();
expect(onClose).toHaveBeenCalledTimes(1);
});
});The flushPromises helper waits one macrotask. That is enough for the awaited mock, the finally block, and the re-render to finish.
When footer buttons are not found
The footer buttons sit in the footer slot of lightning-quick-action-panel. If the default stub does not render that named slot, querySelector returns null and the test fails with a confusing "cannot read properties of null" error. You can fix this by mapping the module to your own stub in jest.config.js.
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
moduleNameMapper: {
'^lightning/quickActionPanel$':
'<rootDir>/force-app/test/jest-mocks/lightning/quickActionPanel.js'
}
};The stub is a small component. Save the first block as quickActionPanel.js and the second as quickActionPanel.html in the same folder.
import { LightningElement, api } from 'lwc';
export default class QuickActionPanel extends LightningElement {
@api header;
}<template>
<slot></slot>
<slot name="footer"></slot>
</template>Testing the headless action
A headless action has no UI, so the test calls the public method directly and checks the toast.
import { createElement } from 'lwc';
import NotifyRecord from 'c/notifyRecord';
describe('c-notify-record', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows a toast naming the record when invoked', () => {
const element = createElement('c-notify-record', { is: NotifyRecord });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
const onToast = jest.fn();
element.addEventListener('lightning__showtoast', onToast);
element.invoke();
const detail = onToast.mock.calls[0][0].detail;
expect(detail.title).toBe('Action ran');
expect(detail.message).toBe('Record 001000000000001AAA was processed');
});
});Common pitfalls
These problems are unrelated to Jest. They show up only when the action runs in an org, so the tests above will not catch them.
| Pitfall | Symptom | Fix |
|---|---|---|
| `actionType` does not match the code | A `Action` component with no `invoke()` does nothing. A `ScreenAction` component that expects headless behavior opens an empty panel. | Use `ScreenAction` for a panel and `Action` only with an `@api invoke()` method. |
| Component not exposed | The component is missing from the Lightning Web Component list when you create the action. | Set `isExposed` to `true` and include the `lightning__RecordAction` target. |
| Reading `recordId` too early | `recordId` is `undefined` in the constructor. | Read it when the user acts, such as inside `handleSave` or `invoke()`. |
| Reusing state between runs | A second click shows old input or a stuck disabled button. | Reset flags such as `isSaving` at the start and in `finally`. Do not assume a fresh instance for every click. |
| No double-click guard | Two saves fire. | Disable the Save button while `isSaving` is true. |
| Closing before the save finishes | The panel disappears and errors are never seen. | Dispatch `CloseActionScreenEvent` only after `await updateRecord` succeeds. |
| Stale data after Apex changes | The record page still shows old values. | `updateRecord` refreshes Lightning Data Service on its own. After Apex DML, call `notifyRecordUpdateAvailable`. |
| Wrong error shape | The toast shows "Unknown error" even though the save failed. | Read `error.body.message` for Lightning Data Service errors. Use `error.body.output` for field-level details when you need them. |
| Hard-coded object | A component using `Account.Description` fails on other objects. | Read `objectApiName` and build fields dynamically, or add the action only to the Account layout. |
A short checklist before you deploy
- The
js-meta.xmlhasisExposedset totrue, the right target, and the rightactionType. - Success, failure, and cancel paths each have a Jest test.
- The Save button is disabled during the save.
- The action is created in Setup and added to the page layout's Salesforce Mobile and Lightning Experience Actions section.
- You tested the action in an org with a user whose profile has the intended field access.
Exercise
Your save test fails with "Cannot read properties of null (reading 'click')" on the Save button. The component works in the org. What is the most likely cause, and how do you fix it?
Show answer
The default lightning-quick-action-panel stub probably does not render the named footer slot, so the buttons inside it never appear in the test DOM. Map lightning/quickActionPanel to a custom stub in jest.config.js with moduleNameMapper. The stub's template renders both a default slot and <slot name="footer"></slot>.
Exercise
A teammate's headless action shows a toast, but the test asserts on the toast before an awaited Apex call finishes, and the test intermittently fails. What two changes make it reliable?
Show answer
Make the test async and await the result of element.invoke(), which works when invoke() is async. If the work is not returned as a promise, call await flushPromises() before asserting. Also mock the Apex method with mockResolvedValue or mockRejectedValue so the outcome does not depend on timing.