Unknown developer
Unknown developer

Reputation: 5930

Mock a custom event

Part of a simple React component:

const doIt=()=>{
    window.dispatchEvent(new CustomEvent('info', {detail: [1,2,3]}));
};
return (
    <button onClick={doIt}>Hello</button>
)

The above custom event is being listened by another component far away in the tree and invokes a callback. I want to write a test about "Hello" button without involving the listener component. How should I mock the event?

Upvotes: 0

Views: 1942

Answers (1)

Owen Pearson
Owen Pearson

Reputation: 469

I would suggest using jest to spy on window.dispatchEvent. you can do this like so:

const mockDispatchEvent = jest.spyOn(window, 'dispatchEvent');

You can then make assertions on the mock like you would normally do with jest:

expect(mockDispatchEvent).toHaveBeenCalledWith(...);

or:

expect(mockDispatchEvent).toMatchSnapshot(...);

Obviously this doesn't test that the event is actually emitted but you you should be able to trust that window.dispatchEvent does its job correctly.

Upvotes: 1

Related Questions