【发布时间】:2020-11-22 20:37:07
【问题描述】:
我正在尝试使用 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)
});
【问题讨论】:
-
由于代码正在运行,这对于codereview.stackexchange.com来说可能是一个更好的问题
标签: reactjs jestjs axios enzyme moxios