Can we simulate an event subscription in LWC unit test? I have a lightning web component using lighting/empApi
like,
export default class ExampleComponent extends LightningElement {
connectedCallback() {
const onMessageCallback = (response) => {
if (this.isSomething) { //Not a public (@api) parameter
//Do something
}
};
subscribe('/event/ExamplePlatformEvent__e', -1, onMessageCallback).then((response) => {
console.log('Successfully subscribed to : ', JSON.stringify(response.channel));
});
}
}
Now, the latest sfdx-lwc-jest
has a stub of lightning/empApi
and I can instantiate the above component with a mock implementation in a test.
describe('c-example-component', () => {
it('test', () => {
const mockResponse = {
"id": "_1583742038741_4782",
"channel": "/event/ExamplePlatformEvent__e",
"replayId": -1
}
const mockEvent = {
"data": {
"schema": "a9SbAGsZvysbJq_U77Mv6Q",
"payload": {
"CreatedById": "00556000004PKXTAA4",
"CreatedDate": "2020-03-09T14:05:35Z",
"SomethingField__c": "ABCDEFG"
},
"event": {
"replayId": 123
}
},
"channel": "/event/ExamplePlatformEvent__e"
}
subscribe.mockImplementation((channel, replayId, onMessageCallback) => {
onMessageCallback(mockEvent);
return Promise.resolve(mockResponse);
});
const element = createElement('c-example-component', {
is: ExampleComponent
});
document.body.appendChild(element);
expect(subscribe.mock.calls[0][0]).toBe('/event/ExamplePlatformEvent__e');
expect(subscribe.mock.calls[0][1]).toBe(-1);
});
});
In the above test, mock subscribe()
is called one time during connectedCallback()
. But how to call onMessageCallback
again after component is rendered? The parameter isSomething
is false for the first time and it will be true by a user operation after component is rendered. So, inside the if clause in onMessageCallback cannot be covered in the current test.