ReferenceError:未使用 jest 测试库定义 BroadcastChannel

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

我在使用反应测试库运行笑话测试用例时遇到错误

javascript reactjs jestjs react-testing-library
2个回答
3
投票

我已经通过以下方式解决了

第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

问题已解决


0
投票

或者,也可以通过 Node 原生

BroadcastChannel
模块使用
"worker_threads"

您需要做的就是在测试中/之前运行它:

self.BroadcastChannel = require('worker_threads').BroadcastChannel;
© www.soinside.com 2019 - 2024. All rights reserved.