Search code examples
javascriptreactjsjestjsreact-testing-library

ReferenceError: BroadcastChannel is not defined using jest testing libray


I'm getting error while runing the jest test case using react-testing library

enter image description here


Solution

  • I have resolved it in following way

    step 1: I have created config/jest.setup.js in root folder and pasted below code in jest.setup.js file

    function channelMock() {}
    channelMock.prototype.onmessage = function () {}
    channelMock.prototype.postMessage = function (data) {
        this.onmessage({ data })
    }
    global.BroadcastChannel = channelMock
    

    step 2: In package.js file we need to add this file path in following way

    "jest": {
            "setupFilesAfterEnv": [
                "./config/jest.setup.js"
            ]
        },
    

    step 3: then you can run the test case using

    npm run test
    

    Issue resolved