Testing global event listener within a React component
window.addEventListener not triggered by Enzyme simulated events
Although many developers working with React consider it an anti-pattern, occasionally, there is the need to listen to an event globally within a React component.
The React Component
In my particular case, I have a React component which renders an entire page of my app and I want to listen when the user hits the Enter
key and do something after this event happens.
Therefore, on componentDidMount
I register the listener to the global window
object and on componentDidUnmount
I unregister.
componentDidMount() {
window.addEventListener('keyup', this.handleKeyUp);
}componentWillUnmount() {
window.removeEventListener('keyup', this.handleKeyUp);
}handleKeyUp(event) {
if (event.key === 'Enter') {
this.handleEnterKey();
}
}
It works perfectly!
The Test
I want to provide tests for this functionality and here the trouble comes.
My testing stack includes Enzyme, therefore I think of using the simulate()
method to mimic the hit of the Enter
key. Surprisingly tho, the event handler is…