DEV Community

Akinn Rosa
Akinn Rosa

Posted on

How to solve 'BroadcastChannel is not defined'

When using BroadcastChannel with React in your application, you probably will face with this issue if try to run some tests with React Testing Library and Jest:

    ReferenceError: BroadcastChannel is not defined

      51 |
      52 |   useEffect(() => {
    > 53 |     authChannel = new BroadcastChannel('auth')
         |     ^

Enter fullscreen mode Exit fullscreen mode

To resolve this, I tried to mock BroadcastChannel creating a broadcast.ts file inside __mocks__ folder with this content:

jest.mock('BroadcastChannel')
Enter fullscreen mode Exit fullscreen mode

Now, you probably will face with this issue:

    Cannot find module 'BroadcastChannel' from 'src/__mocks__/broadcast.ts'

    Require stack:
      src/__mocks__/broadcast.ts

    > 1 | jest.mock('BroadcastChannel')
        | ^
      2 |

Enter fullscreen mode Exit fullscreen mode

Jest can't find BroadcastChannel because is not a module, then, it is necessary install BroadcastChannel module (this helps your tests and help old browsers support).

yarn add broadcast-channel
Enter fullscreen mode Exit fullscreen mode

Then, import BroadcastChannel where you are using (just add import, your code should be the same).

import { BroadcastChannel } from 'broadcast-channel'
Enter fullscreen mode Exit fullscreen mode

In the last step, you need to change you mock file that you created at start to mock broadcast-channel module:

jest.mock('broadcast-channel')
Enter fullscreen mode Exit fullscreen mode

That's It! 🎉

Now your tests should pass and you can work with jest using BroadcastChannel perfectly.

Top comments (2)

Collapse
 
fezvrasta profile image
Federico Zivolo

BroadcastChannel and npm:broadcast-channel have different APIs, you can't swap them out like this. It's even mentioned in the package docs.

Collapse
 
beatrizoliveira profile image
Beatriz Oliveira

Nice!!