我已经通过以下方式解决了
第1步:我在根文件夹中创建了 config/jest.setup.js 并将以下代码粘贴到 jest.setup.js 文件中
function channelMock() {}
channelMock.prototype.onmessage = function () {}
channelMock.prototype.postMessage = function (data) {
this.onmessage({ data })
}
global.BroadcastChannel = channelMock
第2步:在package.js文件中,我们需要按以下方式添加此文件路径
"jest": {
"setupFilesAfterEnv": [
"./config/jest.setup.js"
]
},
第3步:然后您可以使用
运行测试用例npm run test
问题已解决
BroadcastChannel
模块使用 "worker_threads"
。
您需要做的就是在测试中/之前运行它:
self.BroadcastChannel = require('worker_threads').BroadcastChannel;