Enzyme is built for testing React components, it handles React’s synthetic event system quite well (things like onClick events, for example).

But what happens when you want to test event handlers that must be bound to the window ? Interactive components often require these, for keydown events and so on.

A quick solution is to mock the window.addEventListener function implmentation and use it to assign each callback to an object that is easy to call in your tests, to simulate those events firing.

const map = { } ; window . addEventListener = jest . genMockFn ( ) . mockImpl ( ( event , callback ) => { map [ event ] = callback ; } ) ; const component = mount ( < SomeComponent / > ) ; map . keydown ( { key : 'Escape' } ) ;

Source