Sub topic 13
Mock platform modules, labels, and navigation
This chapter assumes you can already create components with createElement, wait for re-rendering, and mock imperative Apex calls. Here you handle the other @salesforce/* and lightning/* imports a component pulls in.
Why platform modules need attention
Jest runs in Node.js. It has no Salesforce runtime, so imports such as @salesforce/label/c.greeting or lightning/navigation cannot resolve to real implementations. sfdx-lwc-jest fills the gap with a resolver and stub modules. Some stubs work with no setup. Others need a mock that you control.
| Import | Default behavior in tests | What you usually do |
|---|---|---|
| `@salesforce/label/c.name` | Resolved automatically to a stub value | Mock it if you assert on the text |
| `@salesforce/user/Id` and similar | Stub value | Mock it if the logic depends on the value |
| `lightning/navigation` | Stub that records calls | Assert on the recorded calls |
| `lightning/platformShowToastEvent` | Real event class | Listen for the dispatched event |
A component to test
This component shows a label, navigates to a record page, and raises a toast.
<template>
<p class="greeting">{greeting}</p>
<button onclick={handleClick}>Open</button>
</template>import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import greetingLabel from '@salesforce/label/c.greeting';
export default class RecordLink extends NavigationMixin(LightningElement) {
@api recordId;
greeting = greetingLabel;
handleClick() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
actionName: 'view'
}
});
this.dispatchEvent(
new ShowToastEvent({
title: 'Opening',
message: 'Opening the record',
variant: 'info'
})
);
}
}Mock a label
Calling jest.mock with { virtual: true } replaces a module that does not exist on disk. Return an object with a default export. Doing this makes the expected text explicit in the test.
Check navigation and toasts
The lightning/navigation stub records each Navigate call. Import getNavigateCalledWith from the same module to read it back. A toast is an ordinary custom event named lightningshowtoast, so you can listen for it on the element.
import { createElement } from 'lwc';
import RecordLink from 'c/recordLink';
import { getNavigateCalledWith } from 'lightning/navigation';
jest.mock(
'@salesforce/label/c.greeting',
() => ({ default: 'Hello from a mock' }),
{ virtual: true }
);
describe('c-record-link', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('renders the label text', async () => {
const element = createElement('c-record-link', { is: RecordLink });
document.body.appendChild(element);
expect(element.shadowRoot.querySelector('.greeting').textContent).toBe(
'Hello from a mock'
);
});
it('navigates to the record and shows a toast', async () => {
const element = createElement('c-record-link', { is: RecordLink });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
const toastHandler = jest.fn();
element.addEventListener('lightningshowtoast', toastHandler);
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
const { pageReference } = getNavigateCalledWith();
expect(pageReference.type).toBe('standard__recordPage');
expect(pageReference.attributes.recordId).toBe('001000000000001AAA');
expect(pageReference.attributes.actionName).toBe('view');
expect(toastHandler).toHaveBeenCalledTimes(1);
expect(toastHandler.mock.calls[0][0].detail.variant).toBe('info');
});
});The first test needs no await. The label is read when the component is created, and no re-render is pending.
Common errors
- "Cannot find module '@salesforce/...'". The module has no automatic stub. Add a virtual
jest.mockfor it. - Label text differs from what you expect. You are reading the stub value. Mock the label to control it.
getNavigateCalledWithreturns stale data. The stub keeps the last call. Reset it between tests or assert right after the click that triggers it.- Toast listener never fires. Attach it to the element before the click, not after.
Exercise
Your component imports @salesforce/user/Id and shows a different message when the ID matches a record owner. How do you test the "owner" branch without an org?
Show answer
Add a virtual mock before importing the component: jest.mock('@salesforce/user/Id', () => ({ default: '005000000000001AAA' }), { virtual: true });. Then set the owner field to the same ID, attach the component, and assert on the rendered message for the owner branch.