Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing BroadcastChannel API using JEST

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' });
like image 237
Asif Iqbal Avatar asked Mar 25 '26 15:03

Asif Iqbal


1 Answers

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;
    })
}
like image 108
Zardoz Avatar answered Mar 28 '26 03:03

Zardoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!