Sub topic 13
Mock platform modules, labels, and navigation
Components import many modules that exist only on the Salesforce platform. Examples are @salesforce/label/..., @salesforce/user/Id, lightning/navigation, and lightning/platformShowToastEvent. Jest runs in Node, outside an org, so it cannot load them directly. This chapter shows how sfdx-lwc-jest supplies stand-ins for these modules, when to override them, and how to assert on navigation and toast behavior.
This chapter assumes you can already write a test that renders a component with createElement, queries its shadow root, and waits a microtask before asserting. It also assumes you know how jest.mock and jest.fn work in general.
How platform imports are resolved
When a component imports a @salesforce/* or lightning/* module, Jest has to find something to load. sfdx-lwc-jest handles this in two ways:
- It transforms scoped imports such as
@salesforce/label/c.Nameso that they fall back to a default value when no real module exists. - It maps
lightning/*imports to stub implementations shipped with the package.
You override a stub only when the default behavior is not enough for your assertion.
The component under test
The examples in this chapter test one component. It shows a custom label and the current user ID, navigates to a record page, and raises a toast.
<template>
<p class="greeting">{greeting}</p>
<p class="user">{userId}</p>
<button class="open" onclick={handleOpen}>Open record</button>
<button class="notify" onclick={handleNotify}>Notify</button>
</template>import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import greeting from '@salesforce/label/c.WelcomeGreeting';
import USER_ID from '@salesforce/user/Id';
export default class WelcomeBanner extends NavigationMixin(LightningElement) {
@api recordId;
greeting = greeting;
userId = USER_ID;
handleOpen() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'view'
}
});
}
handleNotify() {
this.dispatchEvent(
new ShowToastEvent({
title: 'Saved',
message: 'The record was saved.',
variant: 'success'
})
);
}
}Labels and other scoped imports
Custom labels, user IDs, static resources, and similar @salesforce/* imports are replaced by default values. A label import resolves to the label's own path, so @salesforce/label/c.WelcomeGreeting gives you the string c.WelcomeGreeting. This is why a test that asserts on the real label text fails unless you override the module.
| Import | Default in Jest | Typical override |
|---|---|---|
| `@salesforce/label/c.Name` | The string `c.Name` | Virtual mock returning the real text |
| `@salesforce/user/Id` | A fixed placeholder user ID | Virtual mock returning a known ID |
| `@salesforce/resourceUrl/Name` | A placeholder string | Virtual mock if the URL matters |
| `@salesforce/apex/Class.method` | No default behavior you can rely on | Virtual mock with `jest.fn()` (see the Apex chapter) |
| `lightning/navigation` | Stub with test helpers | Use the helpers, not a custom mock |
| `lightning/platformShowToastEvent` | Stub event class | Listen for the dispatched event |
To override a scoped module, call jest.mock with a factory that returns an object with a default key, and pass { virtual: true }. The virtual option tells Jest that no real file exists at that path.
jest.mock(
'@salesforce/label/c.WelcomeGreeting',
() => ({ default: 'Welcome back' }),
{ virtual: true }
);Jest hoists jest.mock calls above the imports, so the override is in place before the component loads. The factory runs in an isolated scope. It cannot reference variables from the test file unless their names start with mock, so use literal values.
Testing navigation
A component that extends NavigationMixin(LightningElement) calls this[NavigationMixin.Navigate](pageReference). In Jest the stub records that call. The stub module exports getNavigateCalledWith, which returns the arguments of the most recent navigate call. The page reference is in the pageReference property.
import { createElement } from 'lwc';
import WelcomeBanner from 'c/welcomeBanner';
import { getNavigateCalledWith } from 'lightning/navigation';
jest.mock(
'@salesforce/label/c.WelcomeGreeting',
() => ({ default: 'Welcome back' }),
{ virtual: true }
);
jest.mock(
'@salesforce/user/Id',
() => ({ default: '005000000000000AAA' }),
{ virtual: true }
);
describe('c-welcome-banner', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
function createBanner() {
const element = createElement('c-welcome-banner', { is: WelcomeBanner });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
return element;
}
it('renders the label and the user ID', async () => {
const element = createBanner();
await Promise.resolve();
expect(element.shadowRoot.querySelector('.greeting').textContent).toBe(
'Welcome back'
);
expect(element.shadowRoot.querySelector('.user').textContent).toBe(
'005000000000000AAA'
);
});
it('navigates to the record page', () => {
const element = createBanner();
element.shadowRoot.querySelector('button.open').click();
const { pageReference } = getNavigateCalledWith();
expect(pageReference).toEqual({
type: 'standard__recordPage',
attributes: {
recordId: '001000000000001AAA',
objectApiName: 'Account',
actionName: 'view'
}
});
});
it('raises a success toast', () => {
const element = createBanner();
const handler = jest.fn();
element.addEventListener('lightning__showtoast', handler);
element.shadowRoot.querySelector('button.notify').click();
expect(handler).toHaveBeenCalledTimes(1);
const toast = handler.mock.calls[0][0].detail;
expect(toast.title).toBe('Saved');
expect(toast.variant).toBe('success');
});
});The navigation test does not need await Promise.resolve(). Clicking the button calls the handler synchronously, and nothing in the assertion depends on re-rendering. The first test does wait, because the DOM is checked after the component connects.
The stub also provides getGenerateUrlCalledWith for components that call this[NavigationMixin.GenerateUrl]. Use it the same way, to check the page reference that was passed in.
Testing toasts
ShowToastEvent is a CustomEvent named lightning__showtoast. The component dispatches it on itself, and the event bubbles to the host element, so element.addEventListener receives it. Read the toast fields from event.detail. You never need to mock the toast module itself.
If your component dispatches the toast from a promise, such as after an Apex call, wait for the promise to settle before you assert, as you do for any asynchronous work.
Wired platform adapters
Some navigation features are wire adapters. CurrentPageReference is the common one. In Jest it is a test wire adapter, so you push data into it with emit:
import { CurrentPageReference } from 'lightning/navigation';
CurrentPageReference.emit({ state: { c__mode: 'edit' } });Call emit after the element is appended. Wait one microtask before you check the DOM, as you would for any wire data.
Modules with no stub
Not every platform module has a stub. If you import a module that sfdx-lwc-jest does not provide, Jest fails with Cannot find module. The usual fix is a virtual mock that exports only what your component uses:
jest.mock(
'lightning/someUnstubbedModule',
() => ({ doWork: jest.fn() }),
{ virtual: true }
);Keep these mocks small. A mock that reimplements the platform tests your mock, not your component.
Common errors
- The label assertion fails with
c.WelcomeGreeting. The default stub returned the label path. Add a virtual mock that returns the text you expect, or assert on the path. - The override does not apply. The module name in
jest.mockmust match the import string exactly. A typo creates an unused mock and leaves the stub in place. ReferenceErrorinside the mock factory. The factory referenced an out-of-scope variable. Inline the value, or rename the variable with amockprefix.getNavigateCalledWithreturns stale data. The recorded call comes from the most recent navigation. If you share state between tests, the previous test's call can leak into the next one. Create a fresh component per test and assert directly after the action.- The toast listener never fires. Add the listener before you click, and listen on the host element for
lightning__showtoast.
Summary of the approach
- Let the default stubs work when your assertions do not depend on the value.
- Use a virtual
jest.mockreturning{ default: value }when the exact label, user ID, or resource URL matters. - Use
getNavigateCalledWithfor navigation, and listen forlightning__showtoastfor toasts. - Use
emiton test wire adapters such asCurrentPageReference. - Add a minimal virtual mock for modules that have no stub.
Exercise
A component imports @salesforce/label/c.SaveLabel and renders it in a button. Your test asserts that the button text is Save changes, but the test fails and shows c.SaveLabel. What is the cause, and how do you fix it?
Show answer
The default stub for a custom label returns the label's path, c.SaveLabel, not the text defined in the org. Add jest.mock('@salesforce/label/c.SaveLabel', () => ({ default: 'Save changes' }), { virtual: true }); at the top of the test file. The virtual: true option is needed because no real module exists at that path. Re-run the test and the button text will be Save changes.
Exercise
Write the assertion that verifies a component navigated to a record page for the record ID 001000000000001AAA after a button click. Which import provides the helper, and why is no await needed before the assertion?
Show answer
Import getNavigateCalledWith from lightning/navigation. After clicking, call const { pageReference } = getNavigateCalledWith(); and then expect(pageReference.attributes.recordId).toBe('001000000000001AAA');. No await is needed when the click handler calls this[NavigationMixin.Navigate] synchronously, because the stub records the call immediately and the assertion does not depend on re-rendering.