Sub topic 13
Testing and Debugging Components That Use LMS
This chapter assumes you can write basic Jest tests for Lightning web components and that you know how @wire, connectedCallback, and disconnectedCallback work. It covers how to test publishers and subscribers, and how to find out why a message never arrives.
What you test
An LMS component has three behaviors worth checking:
- A publisher calls
publishwith the right channel and payload. - A subscriber calls
subscribewhen it connects andunsubscribewhen it is removed. - A subscriber updates its state when its handler receives a message.
You do not need to test Salesforce's message routing. Your tests only check your side of the contract.
Testing with the sfdx-lwc-jest mock
The @salesforce/sfdx-lwc-jest package includes a stub for lightning/messageService. It exports publish, subscribe, and unsubscribe as Jest mock functions, and it exports createMessageContextMock and MessageContext for the wire adapter. Message channels imported from @salesforce/messageChannel/... are also stubbed, so you do not need the channel deployed to run tests.
The next test checks the RecordDetail subscriber from earlier in this tutorial.
import { createElement } from 'lwc';
import RecordDetail from 'c/recordDetail';
import {
subscribe,
unsubscribe,
APPLICATION_SCOPE,
MessageContext
} from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
describe('c-record-detail', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('subscribes on connect with application scope', () => {
const element = createElement('c-record-detail', { is: RecordDetail });
document.body.appendChild(element);
expect(subscribe).toHaveBeenCalledTimes(1);
expect(subscribe.mock.calls[0][1]).toBe(RECORD_SELECTED);
expect(subscribe.mock.calls[0][3]).toEqual({ scope: APPLICATION_SCOPE });
});
it('stores the selected id from a message', () => {
const element = createElement('c-record-detail', { is: RecordDetail });
document.body.appendChild(element);
const listener = subscribe.mock.calls[0][2];
listener({ recordId: '001000000000001' });
expect(element.selectedId).toBeUndefined();
});
it('unsubscribes when removed', () => {
const element = createElement('c-record-detail', { is: RecordDetail });
document.body.appendChild(element);
document.body.removeChild(element);
expect(unsubscribe).toHaveBeenCalledTimes(1);
});
});The second test reads selectedId from the element, but that field is not public, so the assertion shows only that the handler runs without error. To check the value, render it in the template and query the DOM after await Promise.resolve(). You can also expose the field with @api if that fits your design.
The key technique is subscribe.mock.calls[0][2]. It is the callback your component passed to subscribe, so you can call it yourself to simulate an incoming message.
Testing a publisher
For a publisher, assert on the arguments passed to publish.
import { createElement } from 'lwc';
import RecordList from 'c/recordList';
import { publish } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
it('publishes the selected record id', () => {
const element = createElement('c-record-list', { is: RecordList });
document.body.appendChild(element);
element.handleSelect({ currentTarget: { dataset: { id: '001000000000001' } } });
expect(publish).toHaveBeenCalledWith(
expect.anything(),
RECORD_SELECTED,
{ recordId: '001000000000001' }
);
});This sketch calls the handler directly. In a real component, handleSelect is not public, so you normally click an element in the template that triggers it. The first argument is expect.anything() because the message context is a mock object.
Debugging a message that never arrives
When a subscriber stays silent, check the causes below in order.
| Symptom | Likely cause | Check |
|---|---|---|
| Nothing received, no error | Default scope, and the subscriber is not in the active area | Pass `{ scope: APPLICATION_SCOPE }` |
| Channel import fails | Channel not deployed, or the name is missing `__c` | Confirm the metadata is in the org and the import ends in `__c` |
| Handler never fires after a navigation | Subscriber was unsubscribed, or subscribed twice | Log in `connectedCallback` and `disconnectedCallback` |
| Handler fires several times | Duplicate subscriptions | Guard with `if (!this.subscription)` |
| Payload field is `undefined` | Field name differs from the channel metadata | Compare the payload keys with `fieldName` values |
Rather than a diagram, use the following quick procedure in the browser:
- Add
console.logcalls in the publisher just beforepublishand in the subscriber handler. - Open the browser developer tools and confirm the publisher log appears.
- If the subscriber log is missing, confirm that
connectedCallbackran and thatthis.messageContextwas set. - Print the received message with
console.log(JSON.stringify(message))to see the real field names.
Exercise
A subscriber test checks that subscribe was called, but you also want to prove the component reacts to a message. How do you deliver a fake message in Jest?
Show answer
Read the handler from the mock's recorded call, as in subscribe.mock.calls[0][2], then call it with a payload object such as { recordId: '001000000000001' }. After that, await Promise.resolve() and assert on the rendered DOM.