Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Jest: trigger 'addEventListener' 'message' from tests

I have some code my React project which listens to a message event.

const onMessage = ({ data }) => {
  console.log('On onMessage has been fired');
}

window.addEventListener('message', onMessage);

Does anyone know how I can trigger this event from my test suite? I have tried libraries such as events and numerous things such as

test('Recieves message', async () => {
  //Some setup..

  //trigger the addEventListener('message')
  window.parent.postMessage('Hello', '*');  //doesn't work
  window.postMessage('Hello', '*'); //doesn't work
  const ee = new events.EventEmitter();
  ee.emit('Hello') //doesn't work

  //Some further tests...
})

Nothing seems to work. Please note I need to be careful with this test that I do not mock and overwrite all addEventListener. I still need the core code to do what is was intending to do. I simply need to trigger or emit a message event from my tests

like image 980
rottitime Avatar asked Jun 15 '26 12:06

rottitime


1 Answers

In case you want to create a window.postMessage event, you could just leverage the fireEvent react-testing-library api.

You test code will looks like :


import { fireEvent } from '@testing-library/react';


test('Recieves message', async () => {
  // Some setup..

  // trigger the addEventListener('message')
    fireEvent(
      window,
      new MessageEvent("message", { data: { foo: "bar" }, origin: "whatever.com" })
    )

  //Some further tests...
})
like image 113
Alberto S. Avatar answered Jun 17 '26 23:06

Alberto S.