Sub topic 13
Testing and Debugging Components That Use LMS
What this chapter assumes
This chapter assumes you have finished the earlier chapters. You should have a RecordSelected message channel, a publisher (RecordList) and a subscriber (RecordDetail) like the ones you built there. You should also know basic Jest syntax and have a Salesforce DX project. Unit tests use @salesforce/sfdx-lwc-jest, the standard Jest setup for LWC. Install it with npm install @salesforce/sfdx-lwc-jest --save-dev, and run tests with a test:unit script that calls sfdx-lwc-jest.
LMS bugs are hard to spot because a failed message produces no error. A publisher that sends to the wrong channel, or a subscriber that never subscribed, looks the same as a message nobody wanted. Tests and a debugging routine make that silence visible.
What can go wrong
Most LMS problems fall into a few groups:
- Wiring: the channel was not deployed, or the import path is wrong, or the component never gets a
MessageContext. - Lifecycle: the subscriber never subscribed, subscribed twice, or never unsubscribed.
- Scope: the subscriber uses the default scope but sits in a part of the page that is not active.
- Payload: the publisher sends a field name the subscriber does not read.
A unit test can catch lifecycle and payload mistakes. Wiring and scope problems depend on the real org, so you debug those there.
Unit testing with Jest
How the LMS stubs work
sfdx-lwc-jest ships stubs for lightning/messageService. In a test, publish, subscribe and unsubscribe are jest.fn() mocks, and APPLICATION_SCOPE is a constant. Imports from @salesforce/messageChannel/... also resolve to a stub value, so the channel identity you compare in a test is whatever you imported. No real message ever travels between components in Jest. You test each side alone: the publisher calls publish correctly, and the subscriber reacts correctly when you call its handler yourself.
Testing the publisher
Suppose the RecordList template contains a button that carries a record Id:
<template>
<button data-id="001A" onclick={handleSelect}>Select</button>
</template>This test clicks the button and inspects the arguments that reached publish:
import { createElement } from 'lwc';
import RecordList from 'c/recordList';
import { publish } from 'lightning/messageService';
import RECORD_SELECTED from '@salesforce/messageChannel/RecordSelected__c';
describe('c-record-list', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('publishes the selected record id on the RecordSelected channel', () => {
const element = createElement('c-record-list', { is: RecordList });
document.body.appendChild(element);
element.shadowRoot.querySelector('button').click();
expect(publish).toHaveBeenCalledTimes(1);
const [, channel, payload] = publish.mock.calls[0];
expect(channel).toBe(RECORD_SELECTED);
expect(payload).toEqual({ recordId: '001A' });
});
});The test skips the first argument, the MessageContext, because its value in Jest depends on the stub. What matters is the channel and the payload. Using toEqual on the payload also catches a misspelled field name such as recordID.
jest.clearAllMocks() in afterEach matters. Mock call history survives between tests, so without it a later test can pass because of a call that an earlier test made.
Testing the subscriber
Because subscribe is a mock, the callback you pass to it never fires on its own. You pull the callback out of subscribe.mock.calls and call it with a fake message. Give RecordDetail this template:
<template>
<p class="selected">{selectedId}</p>
</template>The tests:
import { createElement } from 'lwc';
import RecordDetail from 'c/recordDetail';
import {
subscribe,
unsubscribe,
APPLICATION_SCOPE
} 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 to the channel with application scope', () => {
const element = createElement('c-record-detail', { is: RecordDetail });
document.body.appendChild(element);
expect(subscribe).toHaveBeenCalledTimes(1);
const [, channel, , options] = subscribe.mock.calls[0];
expect(channel).toBe(RECORD_SELECTED);
expect(options).toEqual({ scope: APPLICATION_SCOPE });
});
it('renders the record id from a received message', async () => {
const element = createElement('c-record-detail', { is: RecordDetail });
document.body.appendChild(element);
const listener = subscribe.mock.calls[0][2];
listener({ recordId: '001A' });
await Promise.resolve();
const text = element.shadowRoot.querySelector('.selected').textContent;
expect(text).toBe('001A');
});
it('unsubscribes when removed from the DOM', () => {
const subscription = { id: 'sub-1' };
subscribe.mockReturnValue(subscription);
const element = createElement('c-record-detail', { is: RecordDetail });
document.body.appendChild(element);
document.body.removeChild(element);
expect(unsubscribe).toHaveBeenCalledWith(subscription);
});
});Three details are worth noting:
- The
await Promise.resolve(): LWC rerenders asynchronously. Without the await, the DOM still shows the old value when you read it. - The mocked return value:
subscribe.mockReturnValue(subscription)makes the stub return a known object. The unsubscribe test can then check that the component hands back the same object it received. - The
{ scope: APPLICATION_SCOPE }check: this assertion guards a decision you made on purpose. If someone deletes the options argument, the component silently falls back to the default scope.
A duplicate subscription test
The if (!this.subscription) guard in connectedCallback exists because a component can connect more than once. Moving it in the DOM disconnects and reconnects it. You can test the guard by appending, removing and appending the same element again, then asserting how many times subscribe ran. After removal, disconnectedCallback sets subscription back to null, so the second connection should subscribe once more. The expected count is 2, with one unsubscribe between them. If you see 1, the component is not cleaning up. If you see 3 or more, the guard is broken.
Debugging in the org
Turn on Debug Mode
Lightning components are minified by default, which makes stack traces hard to read. In Setup, open Debug Mode and enable it for your user. You then get readable source in the browser's developer tools, and you can set breakpoints inside your handleMessage method.
Log at both ends
Temporary console.log calls are the fastest way to find out which side is broken. Log in the publisher just before publish, and at the first line of the subscriber's callback. Then you have three possible results:
- The publisher logs but the subscriber does not: the message was sent and not delivered. Suspect scope, channel name or subscription state.
- Neither logs: the event handler never ran, so the bug is not in LMS.
- Both log but the UI does not change: the payload field name is probably wrong, or the handler does not update a tracked field.
Follow the decision path
Common symptoms
| Symptom | Likely cause | Fix |
|---|---|---|
| Import of `@salesforce/messageChannel/RecordSelected__c` fails on deploy or load | Channel metadata not deployed, or the `__c` suffix is missing | Deploy the `.messageChannel-meta.xml` file and import with the `__c` suffix |
| Subscriber works on one page, not another | Default scope, and the subscriber is not in the active area of the page | Pass `{ scope: APPLICATION_SCOPE }` |
| Aura or Visualforce cannot see the channel | `isExposed` is `false` in the metadata | Set `<isExposed>true</isExposed>` and redeploy |
| Handler runs but the value is `undefined` | Publisher and subscriber disagree on a field name | Compare against the field names in the channel metadata |
| Handler runs twice per message | Two active subscriptions, from a missing guard or a missed unsubscribe | Keep the `if (!this.subscription)` guard and unsubscribe in `disconnectedCallback` |
| Messages arrive after a component is gone | `unsubscribe` was never called | Call `unsubscribe` and reset the field to `null` |
Check the deployed metadata
A channel that works in your scratch org can be missing in a sandbox because it was not part of the deployment. Confirm that RecordSelected.messageChannel-meta.xml is in your package manifest or source folder. Then retrieve it from the target org and compare it with your local file. The fqn value in the metadata is the channel name without the __c suffix. The component import adds the suffix.
Keep payloads simple
If a message arrives with missing or odd data, look at what the publisher actually passed. Plain objects with strings, numbers, booleans and Ids are the safe choice. Functions and DOM elements cannot cross the message boundary. A reactive object from component state may carry wrapper behavior you did not intend. Build a fresh object literal at the publish call, as the RecordList example does, and the problem disappears.
Putting it together
A practical routine for a new LMS feature:
- Write Jest tests for the publisher: channel and payload.
- Write Jest tests for the subscriber: subscribe options, handler behavior, unsubscribe on removal.
- Deploy to a scratch org and place both components on one Lightning page.
- Select a record and watch the console logs from both ends.
- Move the subscriber to a different region or tab and confirm that the scope behaves the way you chose it.
- Remove the console logs.
Exercise
A subscriber unit test calls subscribe.mock.calls[0][2] with { recordId: '001A' } and immediately reads the rendered text, but the text is still empty. The handler is correct. What is missing from the test?
Show answer
The test needs await Promise.resolve() (or another awaited tick) after calling the listener. LWC rerenders asynchronously, so the DOM does not change until the microtask queue has run.
Exercise
A subscriber works on a record page, but when you move the component into a utility bar item, messages stop arriving. The channel is deployed and subscribe runs. What is the most likely cause and the fix?
Show answer
The component subscribes with the default scope, which only delivers messages to subscribers in the active area of the page. A utility bar item is outside it. Pass { scope: APPLICATION_SCOPE } as the fourth argument to subscribe.
Exercise
After navigating back and forth in the app, each message makes the subscriber handler run two or three times. Name two code defects that can cause this and how to check for them in a unit test.
Show answer
Either connectedCallback subscribes without the if (!this.subscription) guard, or disconnectedCallback does not call unsubscribe and reset subscription to null. In Jest, append, remove and re-append the element, then assert on subscribe.mock.calls.length and unsubscribe calls. Expect two subscribes and one unsubscribe between them.