我试图测试一个进行Axios调用的函数,并将返回的数据分配给React组件的状态。 以下是我要测试的代码
class ViewBooking extends Component {
constructor(props) {
super(props);
this.state = {
bookingId: "",
bookingData: [],
errorMessage: ""
};
}
fetchBookingbyID = () => {
const { bookingId } = this.state;
axios.get("http://localhost:4000/bookings/" + bookingId)
.then(response => {
this.setState({ bookingData: response.data});
})
.catch(error => {
this.setState({
errorMessage: "Details of "+bookingId + " is not found!"
});
});
}
}
我编写的测试用例如下:
test("Axios GET request : fetchBookingbyID", async () => {
const wrapper = shallow(<ViewBooking />);
var mock = new MockAdapter(axios);
const mockData2 = {
id: 1001,
buffetName: "BBQ Special",
emailId: "absy@gmail.com"
};
mock.onGet("http://localhost:4000/bookings/1001").reply(200, mockData2);
wrapper.setState({ bookingId: 1001 });
await wrapper.instance().fetchBookingbyID();
expect(wrapper.state().bookingData).toEqual(mockData2)
});
现在,即使删除了用fetchBookingbyId()方法编写的代码,该测试用例也始终可以通过。