Reputation: 2471
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
Upvotes: 7
Views: 10938
Reputation: 2115
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...
})
Upvotes: 12
Reputation: 102497
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
Upvotes: 1