I have implemented cross-browser tab communication using the broadcast channel API in my React Project. It's working as expected in the browser, but I am struggling to write unit tests for it using JEST. When I run the test case, the post message gets called, but the onmessage function never gets called. Can anyone help me?
const channel = new BroadcastChannel('some-name');
channel.onmessage = function(e) {
// some code
}
channel.postMessage({ message: 'some message' });
I knocked up a quick mock for this for my purposes (this is typescript):
using jest...
// A basic mock of BroadcastChannel as node is missing it. Doesn't do everything...
if (!global.BroadcastChannel) {
global.BroadcastChannel = jest.fn(function (name: string) {
const channel = {
name,
postMessage: jest.fn(function (message: any) {
try {
JSON.parse(JSON.stringify(message))
} catch (exception) {
if (typeof channel.onmessageerror === 'function') {
channel.onmessageerror(message);
}
}
if (typeof channel.onmessage === 'function') {
channel.onmessage(message);
}
}),
close: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
onmessage: jest.fn(),
onmessageerror: jest.fn(),
};
return channel;
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With