Sub topic 14
Testing with Jest and avoiding common pitfalls
This chapter assumes you have a working screen action like the updateDescription component from earlier chapters. It also assumes @salesforce/sfdx-lwc-jest is installed in your Salesforce DX project. Jest runs your component in a simulated DOM, so it can check your logic. It cannot check how the platform opens the panel or passes recordId. You still need to test those in an org.
What to test
A screen action has three behaviors worth testing:
- On success, it calls
updateRecordwith the record ID and the new description. - On success, it dispatches a success toast and a close event.
- On failure, it dispatches an error toast and does not close the panel.
You replace updateRecord with a mock, so no org is involved. Each event is a CustomEvent that you can listen for on the component element.
A Jest test for the screen action
Save this as force-app/main/default/lwc/updateDescription/__tests__/updateDescription.test.js.
import { createElement } from 'lwc';
import UpdateDescription from 'c/updateDescription';
import { updateRecord } from 'lightning/uiRecordApi';
jest.mock(
'lightning/uiRecordApi',
() => ({ updateRecord: jest.fn() }),
{ virtual: true }
);
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
function setup() {
const element = createElement('c-update-description', { is: UpdateDescription });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
return element;
}
function typeDescription(element, text) {
const textarea = element.shadowRoot.querySelector('lightning-textarea');
textarea.value = text;
textarea.dispatchEvent(new CustomEvent('change'));
}
function clickSave(element) {
const buttons = element.shadowRoot.querySelectorAll('lightning-button');
Array.from(buttons).find((b) => b.label === 'Save').click();
}
describe('c-update-description', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('saves the description, shows a toast, and closes', async () => {
updateRecord.mockResolvedValue({});
const element = setup();
const toastHandler = jest.fn();
const closeHandler = jest.fn();
element.addEventListener('lightning__showtoast', toastHandler);
element.addEventListener('lightning__actionsclosescreen', closeHandler);
typeDescription(element, 'New text');
clickSave(element);
await flushPromises();
expect(updateRecord).toHaveBeenCalledTimes(1);
const { fields } = updateRecord.mock.calls[0][0];
expect(fields.Id).toBe('001000000000001AAA');
expect(fields.Description).toBe('New text');
expect(toastHandler.mock.calls[0][0].detail.variant).toBe('success');
expect(closeHandler).toHaveBeenCalledTimes(1);
});
it('shows an error toast and stays open when the save fails', async () => {
updateRecord.mockRejectedValue({ body: { message: 'Boom' } });
const element = setup();
const toastHandler = jest.fn();
const closeHandler = jest.fn();
element.addEventListener('lightning__showtoast', toastHandler);
element.addEventListener('lightning__actionsclosescreen', closeHandler);
clickSave(element);
await flushPromises();
expect(toastHandler.mock.calls[0][0].detail.variant).toBe('error');
expect(toastHandler.mock.calls[0][0].detail.message).toBe('Boom');
expect(closeHandler).not.toHaveBeenCalled();
});
});Run it with npx sfdx-lwc-jest -- --watchAll=false. The flushPromises helper waits for the async handleSave to finish before the assertions run.
For a headless action, create the element and call element.invoke() directly. Then check the toast event. Nothing renders, so there is no DOM to query.
Common pitfalls
| Symptom | Likely cause | Fix |
|---|---|---|
| Action missing from the layout | `isExposed` is false, or the target is wrong | Set `isExposed` to `true` and use `lightning__RecordAction` |
| Screen action behaves like a headless one, or the reverse | `actionType` does not match the component | Use `ScreenAction` for a panel and `Action` for `invoke()` |
| Nothing happens on a headless action | `invoke` is missing `@api` | Declare it as `@api invoke()` |
| `recordId` is `undefined` | The component is used as a global action | Global actions have no record context. Do not rely on `recordId` |
| Panel never closes | No `CloseActionScreenEvent` on the success path | Dispatch it after the save succeeds |
| Save button stays disabled | `isSaving` is not reset on failure | Reset it in `finally`, as the example does |
| Record page shows old values after an Apex change | Lightning Data Service does not know about server-side changes | Call `notifyRecordUpdateAvailable` |
Exercise
In the failure test above, why do we assert that the close handler was not called, and which part of the component makes that true?
Show answer
A failed save should leave the panel open so the user can read the error and retry. The catch block only dispatches an error toast. The CloseActionScreenEvent is dispatched only inside the try block after updateRecord succeeds, so a rejected promise skips it.