I have a function called onFormSubmit in parent component. I pass this function to child component. Upon form submit in child component, onFormSubmit function inside child component is called to pass a value back to parent component. Then this onFormSubmit function does some kind of checking and based on that, updates the state in parent component.
I want to mock/stub out this ajax/api call. How can I achieve this? Or how do I write my code in such a way that this scenario is testable.
My Parent component looks like this:
class App extends React.Component {
state: { message: "" }; //I want to test the state of message
onFormSubmit = async (form) => {
if (form.primaryEmail !== "") {
const response = await axios.post("api/", form);
this.setState(
{
message: (response.status === 200) ? "Your email has been updated." : ""
});
} else {
this.setState({ message: "No Update" });
}
}
render() {
return (
<div>
<Child onSubmit={this.onFormSubmit} />
<h4>{this.state.message}</h4>
</div>
);
}
}
My Child Component looks like this:
class Child extends React.Component {
state = {
primaryEmail: "",
};
onPrimaryEmailChange = e => {
this.setState({ primaryEmail: e.target.value });
}
onFormSubmit = e => {
e.preventDefault();
this.props.onSubmit(this.state); //passing the value back to parent component
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h3>Email Address</h3>
<div>
<input type="email" value={this.state.primaryEmail} onChange={this.onPrimaryEmailChange} />
</div>
<div>
<button type="submit">Submit</button>
</div>
</form >
);
}
}
My test looks like this:
test("When valid form is submitted, it should show a success message", () => {
const wrapper = mount(<App />);
wrapper.find("input").at(0).simulate("change", {
target: {
value: "a@b.c",
}
});
wrapper.find('form').simulate('submit');
expect(wrapper.state('message')).toEqual('Your email has been updated.');
});
I get this error:
Expected value to equal:
"Your email has been updated."
Received:
""