It is possible to use Enzyme's method .simulate() on custom events. For Example:
// Code
<Element onFoo={someFunction}></Elements>
// Test
const element = shallow(<Element>);
element.simulate('foo');
Is this the way custom events should be tested with Enzyme or is it a better approach to use s.th. like:
//Test
const element = shallow(<Element>);
element.props.onFoo()
It is possible to use Enzyme's method .simulate() on custom events. For Example:
// Code
<Element onFoo={someFunction}></Elements>
// Test
const element = shallow(<Element>);
element.simulate('foo');
Is this the way custom events should be tested with Enzyme or is it a better approach to use s.th. like:
//Test
const element = shallow(<Element>);
element.props.onFoo()
Share
Improve this question
asked Sep 29, 2016 at 9:58
FrankFrank
1611 gold badge1 silver badge7 bronze badges
5 Answers
Reset to default 7It seems that .simulate()
for custom events is not implemented. There is an issue on github, where this topic is discussed and one of the Enzyme maintainers suggests to use the second approach you've provided:
wrapper.find(Child).prop('customEvent')(fakeEvent)
You can use .simulate()
on custom events. There is a catch that you have to use on
as a prefix for the custom event. For eg. onJump
, onAdd
is how you have to name your custom events.
element.props.onFoo()
in the above case is not really testing the functionality. It only tests the internals of component so the binding remains untested. Also it becomes difficult to refactor as implementation is coupled with test code.
You can refer to this blog for a working demo of the scenario and how components having custom events can be tested.
In addition to the other answers, if you are testing a parent component that uses your Element
component:
Not sure if this is a matter of version as well. But I'm working with enzyme 2.9.1 and this is how I accomplish to trigger a child custom function:
wrapper.find(Child).prop('customEvent')(/*args*/)
But isn't it actually already working in the current shallow rendering?
/* Film component */
render() {
return (
...
<FilmHeader onSearchClick={this.handleSearchClick}>
...
)
}
/* Test */
const wrapper = shallow(<Film {...props} />);
wrapper.find('FilmHeader').simulate('searchClick');
The aforementioned enzyme issue is still open though. And documentation doesn't state anything obvious about this feature. So maybe the issue is the documentation itself.
What worked for me, trying to siumlate a custom event on a component that is not the top-level component was as follows:
const myComponent = enzymeWrapper.find('MyComponent');
myComponent.node.onThingSelected({}, { thing: newThing});
Where myComponent is a React component, onThingSelected is the custom event handler exactly as named on the component, and newThing is an object of the type expected by the event handler.