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()
import React from 'react'; import { shallow } from 'enzyme'; import Button from './Button'; describe('Test Button component', () => { it('Test click event', () => { const mockCallBack = jest. fn(); const button = shallow((<Button onClick={mockCallBack}>Ok! </Button>)); button. find('button').
Simulate a Click Event In the test, we create a ref so that we can pass it to the rendered Button and later to the Simulate. click call. The onClick prop gets the value of a handleClick event handler function. That function calls done() , which is the callback to the it function`.
Basically, we need to create a spy function that will trigger the simulated response. To do that, we use jest. fn – from Jest. Once we have the spy, we can test the feature using toHaveBeenCalled or toHaveBeenCalledWith – also from Jest – to check if the spy was called or not.
It 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)
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*/)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With