React Jest: trigger 'addEventListener' 'message' from tests
Asked Answered
H

2

7

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

Hudnall answered 12/8, 2021 at 11:5 Comment(0)
F
12

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...
})
Facial answered 30/5, 2022 at 10:19 Comment(0)
H
1

From the docs 8. queue-a-global-task and this issue. There is a hack way, you need to flush the microtasks from message queue.

E.g.

main.ts:

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

window.addEventListener('message', onMessage);

main.test.ts:

function flushMessageQueue(ms = 10) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
describe('68756255', () => {
  test('Recieves message', async () => {
    require('./main');
    window.postMessage('Hello', '*');
    await flushMessageQueue();
  });
});

test result:

 PASS  examples/68756255/main.test.ts (9.111 s)
  ● Console

    console.log
      On onMessage has been fired

      at onMessage (examples/68756255/main.ts:2:11)


Test Suites: 1 skipped, 1 passed, 1 of 2 total
Tests:       2 skipped, 1 passed, 3 total
Snapshots:   0 total
Time:        10.918 s
Holliholliday answered 13/8, 2021 at 3:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.