enzyme: Focus event simulation not working as expected.
Hello!
With enzyme version ^2.9.1.
Given a test written as such:
it('fires onFocus handler when user clicks away from input', () => {
const component = mount(<Component />, { context });
component.instance().onFocus = jest.fn();
component.find('input').simulate('focus');
expect(component.instance().onFocus).toHaveBeenCalledTimes(1);
});
And the component render (only relevant part left in):
<input
onFocus={this.onFocus}
type="search"
maxLength="100"
/>
The test states that the onFocus callback has never been called. However, the following works as expected:
<input
onFocus={() => this.onFocus()}
type="search"
maxLength="100"
/>
Thank you.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 8
- Comments: 23 (10 by maintainers)
I would discourage using simulate at all; try
component.find('input').prop('onFocus')()instead.Just found this. I want to chime in and say if you do use this solution,
component.find('input').prop('onFocus')(), you will lose access to the event object in the callback. To fix this would be to usecomponent.find('input').simulate('focus').For one, events don’t bubble; for another, simulating “change” doesn’t also trigger all the key events that led to it.
Invoking a prop explicitly, and passing your own event object, is the proper way to test things.
Based on the documentation,
simulate('click')and.prop('onClick')()should work in the same way, I guess.@QuantumInformation
.prop('onChange')()