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
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...
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With