[英]How would one mock an axios.all request?
我在嘲笑我的项目时遇到了这堵墙。
我提出了一个 axios.all 请求,其中包含 10 个请求。 我他妈的怎么嘲笑它?
我目前正在使用 moxios 来模拟我的 axios http 请求,但它似乎没有处理这个问题的功能。
示例:
axios.all([
axios.get(url1),
axios.get(url2),
axios.get(url3)
])
.then(axios.spread(function (r1, r2, r3) {
...
}))
.catch(err => {
console.error(err, err.stack);
});
有没有人遇到过这个问题并找到了解决方案?
更新:
我只是单独嘲笑了每个请求,但这是一个缓慢而痛苦的过程,有没有更快更有效的方法来做到这一点?
我解决这个问题的方法是使用async
和await
来确保函数在执行断言之前等待它完成运行。
我没有使用 moxios,而是使用 axios -mock-adapter,但我觉得这个问题可以用同样的方式解决。
鉴于上述问题,我是这样解决的......
在我的组件中,我有一个像这样的方法
getTheThing () {
axios
.all([
axios.get(`/api/endpoint/1`),
axios.get(`/api/endpoint/2`)
])
.then(
axios.spread((response1, response2) => {
this.setState({
firstThing: response1.data,
secondThing: response2.data
})
})
)
}
在我的测试中...
mock = new MockAdapter(axios)
mock
.onGet(url1)
.reply(200, mockData1)
.onGet(url2)
.reply(200, mockData2)
it('should set issue state after fetching the requested issue', async () => {
await component.instance().getTheThing()
expect(whateverItIsYoureExpecting)
})
这就是我最终嘲笑它的方式。 在这种情况下, axios.all
有 2 个调用。 mockAxios 将循环两次。 我使用了axios-mock-adapter
包。
Axios 调用(这也适用于Promise.all
)
axios.all[
await axios.get('endpoint1'),
await axios.get('endpoint1'),
]
模拟
const mockData1 = [1, 2, 3];
const mockData2 = [3, 2, 1];
MockAxios.onAny().reply(config => {
// Use your config to return different responses.
// This mock will loop through every request in the Promise.all
if(config.url === 'endpoint1') {
return [200, {data: mockData1}, config];
} else if(config.url === 'endpoint2') {
return [200, {data: mockData2}, config];
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.