Org Skills

Jest mocks for `lightning/*` modules

Supporting material for salesforce-frontend-testing. Agents load it on demand; it ships inside the skill folder.

RawSource

Target: @salesforce/sfdx-lwc-jest (Spring '26). Sources: Test Lightning Web Components, salesforce/sfdx-lwc-jest stubs, trailheadapps/lwc-recipes jest-mocks.

sfdx-lwc-jest already stubs every lightning/* module through its resolver. Write a mock only when the test needs to observe what the component did with it, and then map that one module in jest.config.js.

1. lightning/navigation

force-app/test/jest-mocks/lightning/navigation.js:

import { createTestWireAdapter } from '@salesforce/wire-service-jest-util';

export const CurrentPageReference = createTestWireAdapter(jest.fn());

const Navigate = Symbol('Navigate');
const GenerateUrl = Symbol('GenerateUrl');

export const mockNavigate = jest.fn();
export const mockGenerate = jest.fn();

export const NavigationMixin = (Base) =>
    class extends Base {
        [Navigate](pageReference, replace) {
            mockNavigate({ pageReference, replace });
        }
        [GenerateUrl](pageReference) {
            mockGenerate({ pageReference });
            return Promise.resolve('https://www.example.com');
        }
    };
NavigationMixin.Navigate = Navigate;
NavigationMixin.GenerateUrl = GenerateUrl;

export const getNavigateCalledWith = () =>
    mockNavigate.mock.calls.length === 0
        ? { pageReference: undefined, replace: undefined }
        : mockNavigate.mock.lastCall[0];

In the test:

import { getNavigateCalledWith } from 'lightning/navigation';

element.shadowRoot.querySelector('a.order-link').click();
await flushPromises();

const { pageReference } = getNavigateCalledWith();
expect(pageReference.type).toBe('standard__recordPage');
expect(pageReference.attributes.recordId).toBe('0011x00000abcDEF');

2. lightning/messageService

force-app/test/jest-mocks/lightning/messageService.js:

export const APPLICATION_SCOPE = Symbol('APPLICATION_SCOPE');
export const createMessageContext = jest.fn();
export const releaseMessageContext = jest.fn();
export const publish = jest.fn();
export const subscribe = jest.fn();
export const unsubscribe = jest.fn();
export const MessageContext = jest.fn();

Publisher test: assert publish was called with the channel and payload. Subscriber test: pull the handler out of the mock and call it directly.

import { subscribe, publish } from 'lightning/messageService';
import ORDER_SELECTED from '@salesforce/messageChannel/Order_Selected__c';

it('updates when a message arrives', async () => {
    const element = createElement('c-order-detail', { is: OrderDetail });
    document.body.appendChild(element);

    const handler = subscribe.mock.calls[0][2];      // (context, channel, handler, config)
    handler({ orderId: '801xx0000000001' });
    await flushPromises();

    expect(element.shadowRoot.querySelector('h2').textContent).toContain('801xx0000000001');
});

Note: a message channel import (@salesforce/messageChannel/…) needs no jest.mock; the resolver stubs it.

3. Toasts, modals and refresh

// force-app/test/jest-mocks/lightning/platformShowToastEvent.js
export const ShowToastEventName = 'lightning__showtoast';
export class ShowToastEvent extends CustomEvent {
    constructor(config) {
        super(ShowToastEventName, { composed: true, cancelable: true, bubbles: true, detail: config });
    }
}
// asserting a toast
const handler = jest.fn();
element.addEventListener(ShowToastEventName, handler);
// …trigger the action…
expect(handler).toHaveBeenCalled();
expect(handler.mock.calls[0][0].detail.variant).toBe('error');

For lightning/modal, mock the module's open as a jest.fn() returning the result the component expects (Promise.resolve('ok')), and assert both the call and what the component did with the result. For lightning/refresh, mock RefreshEvent the same way as ShowToastEvent and listen for 'lightning__refreshview'.

4. LDS adapters need no mock

import { getRecord } from 'lightning/uiRecordApi';
const mockGetRecord = require('./data/getRecord.json');   // a UI API snapshot

const element = createElement('c-order-summary', { is: OrderSummary });
element.recordId = '801xx0000000001';
document.body.appendChild(element);
getRecord.emit(mockGetRecord);
await flushPromises();

Take the JSON from a real /ui-api/records/{id} response rather than writing it by hand — hand-written LDS payloads miss the fields.X.value / displayValue shape and produce tests that pass against fiction.

updateRecord and friends are plain mocks on the stub: import { updateRecord } from 'lightning/uiRecordApi' and assert toHaveBeenCalledWith({ fields: { Id: …, Status__c: 'Approved' } }).

5. GraphQL wires

import { graphql } from 'lightning/uiGraphQLApi';
const mockGraphQL = require('./data/openOrders.json');

graphql.emit(mockGraphQL);            // graphql is an LDS-style test wire adapter
await flushPromises();

The emitted shape must match the real envelope ({ data: { uiapi: { query: { … } } }, errors: [] }), so snapshot it from an org rather than inventing it.

6. refreshApex and refresh assertions

jest.mock('@salesforce/apex', () => ({ refreshApex: jest.fn(() => Promise.resolve()) }), { virtual: true });
import { refreshApex } from '@salesforce/apex';
// …trigger the mutation…
expect(refreshApex).toHaveBeenCalled();

notifyRecordUpdateAvailable is on the lightning/uiRecordApi stub and can be asserted directly:

import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
expect(notifyRecordUpdateAvailable).toHaveBeenCalledWith([{ recordId: '801xx0000000001' }]);

7. Common failures and their cause

Symptom Cause
getOrders.emit is not a function Wired Apex mocked as a bare jest.fn() — use createApexTestWireAdapter
expect(...).toBeAccessible is not a function sa11y setup file not registered, usually setupFilesAfterEach instead of setupFilesAfterEnv
Cannot find module 'lightning/…' A wildcard moduleNameMapper pointing at a mocks folder that has no file for that module
Assertions see the old DOM Missing await flushPromises() (one microtask tick is enough after emit)
Wire emits but nothing renders emit called before document.body.appendChild(element)
State leaks between tests No DOM reset and no jest.clearAllMocks() in afterEach