In react, when you have an element with an onClick prop, it's easy to use Enzyme's .simulate("click")
method to click it. However, there's an example in my codebase where an element is referenced by React's "ref" prop, and then that element's .addEventListener
is invoked to bind an event handler to it.
I've provided a code example:https://codesandbox.io/s/1z4xok048j
The key line is this:
if (this.refs.hey) {
this.refs.hey.addEventListener("click", this.handleClick);
}
In the code example, the eventHandler is not bound until componentDidUpdate is run, so if you click on the "click me to increment counter" div, the child element receives new props and its componentDidUpdate triggers. Then if you click on the Child element, its eventHandler triggers as expected. However, I can't reproduce this behavior in my Enzyme/Jest tests.
I've done the obvious .simulate("click")
method from Enzyme and it does not work; when I change from using refs and the event listeners to using an onClick
, .simulate("click")
works as expected. However, removing the refs causes other bugs to surface and I haven't been able to figure out why, so I'd prefer to find out a way to simulate clicking the button.