This one has me totally stumped despite trying everything.
I am testing a React component with Jest/Enzyme. This test simulates modifying a element which then calls an onChange method.
When I run test I get this from Jest:
Cannot spy the onChange property because it is not a function; undefined given instead
Why??
Here are the key parts of the component:
import React, {Component} from 'react';
import EntitiesPulldown from './entities-pulldown'
class NewTransactionForm extends Component {
constructor(props) {
super(props);
this.state = {
amount: "0.00",
investors_4_picklist: [],
selectedTType:0
};
this.onChange = this.onChange.bind(this);
}
onChange(event) {
const value = event.target.value;
const name = event.target.name;
this.setState({
[name]: value
});
console.log("just set "+name+" to "+value)
}
render() {
return (
<div>
<EntitiesPulldown
itemList = {this.state.investors_4_picklist}
handleChangeCB = {this.onChange}
/>
</div>
)
}
}
export default NewTransactionForm;
Pretty straightforward. And here is the test:
test('NTF calls onChange after select', () => {
const wrapperInstance = mount(<NewTransactionForm />).instance();
const spy = jest.spyOn(wrapperInstance, 'onChange') //fails
wrapperInstance.update().find('select').simulate('change',{target: { name: 'selectedTType', value : 3}});
expect(spy).toHaveBeenCalled();
});
And I also tried this option, same results:
const spy = jest.spyOn(NewTransactionForm.prototype, 'onChange')
What am I doing wrong? Any help really appreciated.
wrapperInstance
is the object you expect it to be, and that you aren't doing something like accidentally importing the wrong component... – Garrett Motznerjest.spyOn(wrapperInstance.prototype, 'onChange')
– evolutionxbox