I have a component that dispatches an event on load. The listener is outside the component, in this case a Unit Test listening to the event.
const User = () => {
useEffect(() => {
dispatchEvent(new CustomEvent('mounted', {detail: {foo: "bar"}}));
}, [])
}
Attempt – bubbles property didn’t work
component
const User = () => {
useEffect(() => {
dispatchEvent(new CustomEvent('mounted', { bubbles: true, detail: {foo: "bar"}}));
}, [])
}
Unit Test
it("should get event", () => {
return new Promise(resolve => { // return promise so runner waits on it.
console.log('promise'); // called
window.addEventListener("mounted", event => {
console.log("listener"); // not called
expect(event.detail.foo).equal("bar");
resolve();
});
act(() => {
render(<UserList />);
});
});
});
3
It looks like you expect your event to bubble up the chain of nodes. You should mention it explicitly when creating the event:
let evtMounted = new CustomEvent('mounted', {
bubbles: true,
detail: "some value, different for each SUT"
});
dispatchEvent(evtMounted);
return () => {
evtUnmounted = new CustomEvent('unmounted', { bubbles: true });
dispatchEvent(evtUnmounted);
}
link to MDN post: event bubbling
5