使用 JEST 测试 BroadcastChannel API

问题描述 投票:0回答:1

我在我的 React 项目中使用广播通道 API 实现了跨浏览器选项卡通信。它在浏览器中按预期工作,但我正在努力使用 JEST 为其编写单元测试。当我运行测试用例时,post 消息被调用,但 onmessage 函数永远不会被调用。有人可以帮助我吗?

const channel = new BroadcastChannel('some-name');

channel.onmessage = function(e) {
  // some code

}

 channel.postMessage({ message: 'some message' });
javascript reactjs unit-testing jestjs broadcast-channel
1个回答
0
投票

为了我的目的,我为此做了一个快速模拟(这是打字稿):

开玩笑...

// BroadcastChannel 作为节点的基本模拟丢失了。不做所有事情...

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;
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.