我正在尝试使用moxios模拟函数中的axios请求。测试运行得很好,并得到了预期的结果,但我不认为他们实现它的方式根本不是一个最佳实践。有人能给我推荐一种比在测试中使用setTimeout()更好的方法来实现这一点吗?
....
componentDidMount() {
this.fetchSomething();
}
fetchSomething = () => {
Axios.get('https://someurl.com/api/1')
.then((response) => {
this.setState({ data: response.data.data });
})
.catch((error) => {
this.setState(error);
})
}
....我写的测试:
beforeEach(() => {
moxios.install();
});
afterEach(() => {
moxios.uninstall();
})
it('should ', async (done) => {
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { data: 'hello' }
})
});
const wrapper = shallow(<TestComponent />);
setTimeout(() => {
expect(wrapper.instance().state.data).toEqual('hello')
done();
}, 500)
});发布于 2020-08-03 02:11:01
我认为这是一个更好的选择。
it('should ', (done) => {
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { data: 'hello'}
}).then(() => {
expect(wrapper.instance().state.data).toEqual('hello');
done()
})
});
});
const wrapper = shallow(<TestComponent />);https://stackoverflow.com/questions/63218239
复制相似问题