I am trying to mock functions from React Class component using Jest/Enzyme
Here is the source code
import React, { Fragment, Component } from "react";
import { withStyles } from "@material-ui/core/styles";
...
const useStyles = (theme) => ({
// styles
});
class K8sIPCalculator extends Component {
constructor(props) {
super(props);
this.state = {
data: JSON.parse(JSON.stringify(initialState)),
};
}
handleInputChange = (path, value) => {
const newData = { ...this.state.data };
newData[path] = value;
this.setState({ data: newData });
};
calculate = (event) => {
event.preventDefault();
// does some calculation
this.setState({ data: newData });
};
onReset = () => {
this.setState({ data: JSON.parse(JSON.stringify(initialState)) });
};
render() {
const { classes } = this.props;
return (
<Fragment>
<form
className={classes.formRoot}
onSubmit={(event) => this.calculate(event)}
>
<InputLabel className={classes.label}>Nodes:</InputLabel>
<TextField
required
size="small"
type="number"
InputProps={{
inputProps: {
min: 0,
},
}}
onChange={(e) =>
this.handleInputChange("nodes", e.target.value)
}
id="nodes-input"
value={this.state.data.nodes}
/>
</form>
</Fragment>
);
}
}
export default withStyles(useStyles, { withTheme: true })(K8sIPCalculator);
I want to mock handleInputChange
, onReset
, calculate
functions and check if it has been called or not and also it has been called with what arguments.
I have tried these methods.
const wrapper = mount(<K8sIPCalculator />);
const spy = jest.spyOn(wrapper, "handleInputChange");
Error: Cannot spy the handleInputChange property because it is not a function; undefined given instead
const spy = jest.spyOn(wrapper.instance(), "handleInputChange");
or wrapper.instance().handleInputChange = jest.fn();
Error: Cannot set property 'handleInputChange' of null
const spy = jest.spyOn(K8sIPCalculator.prototype, "handleInputChange");
Error: Cannot spyOn on a primitive value; undefined given
expect(spy).toHaveBeenCalled();