I am testing a React component that has several nested components within. My tests aim to make sure each component is given the right props. One of those components should be passed an onChange function, so I tried to do the following (inside test()
):
Jest + Enzyme Test:
const props = {
onSomethingChange: jest.fn()
};
const component = shallow(<MyComponent {...props} />);
expect(component.find('SomeNestedComponent')
.prop('onSomethingChange')).toBe(props.onSomethingChange);
The test fails with the following (note: I also tried .toEqual
):
Expected value to equal:
[Function mockConstructor]
Received:
[Function anonymous]
The definition for my component follows:
MyComponent
class MyComponent extends Component {
onSomethingChange = (event) => {
// do something
}
render() {
return (
<div>
<Header />
<SomeNestedComponent onSomethingChange={this.onSomethingChange} />
<Footer />
</div>
);
}
}
How can I make sure the correct function is passed as prop (and not just any other function)? Note that I don't call the function anytime; I just define it.
I found out what is wrong with the construct in the question. The problem is the onSomethingChange
function is a component instance method and not a prop of the MyComponent
component itself. So the onSomethingChange
prop in SomeNestedComponent
was referring to the onSomethingChange
method in MyComponent
(thus not being equal to its prop set up in the test). The fix is to simply compare SomeNestedComponent
's prop to MyComponent
's instance method as follows:
expect(component.find('SomeNestedComponent')
.prop('onSomethingChange')).toBe(component.instance().onSomethingChange);
The instance() function will allow you to get all the functions available within the component.
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