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