考虑以下代码:
class Dashboard extends Component {
state = {
fileName: "",
group: "",
country: "",
error: ""
};
onFormSubmit = async e => {
e.preventDefault();
const { group, country } = e.target;
try {
await axios.post("/api/dashboard", {
name: group.value,
country: country.value,
image: this.state.fileName
});
} catch (error) {
console.log(error.response.data.message);
this.setState({ error: error.response.data.message });
}
};
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
type="text"
onChange={this.onGroupChange}
name="group"
placeholder="Group Name"
value={this.state.group}
/>
{this.state.error}
<input
type="text"
onChange={this.onCountryChange}
name="country"
placeholder="Country"
value={this.state.country}
/>
<ImageUpload
fileName={this.state.fileName}
onFileNameChange={this.onFileNameChange}
/>
<button type="submit">Add Group</button>
</form>
</div>
);
}
}
当发布请求失败时,我正在尝试测试error
状态是否设置为适当的值。这是到目前为止的测试:
it("should set error state when dashboard api returns error", async () => {
const errorMsg = "Group already exist";
moxios.stubRequest("/api/dashboard", {
status: 400,
response: {
message: errorMsg
}
});
const event = {
preventDefault: () => {},
target: {
group: "",
country: ""
}
};
const wrapper = shallow(<Dashboard />);
await wrapper.find("form").simulate("submit", event);
console.log(wrapper.state("error").value);
expect(wrapper.state("error")).toBe(errorMsg);
});