【问题标题】:How would one mock an axios.all request?如何模拟 axios.all 请求?
【发布时间】:2018-03-16 21:47:36
【问题描述】:

我在嘲笑我的项目时碰到了这堵墙。

我发出一个 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);
});

有没有人遇到过这个问题并找到了解决方案?

更新:

我只是单独模拟了每个请求,但这是一个缓慢而痛苦的过程,有没有更快更有效的方法来做到这一点?

【问题讨论】:

  • 我目前正在努力解决同样的问题。您找到解决方案了吗?
  • @mazedlx 我最终只是使用 moxios 模拟每个请求并使用 stubrequest 方法模拟每个请求。不是最好的解决方案。

标签: javascript unit-testing mocking axios moxios


【解决方案1】:

我解决这个问题的方法是使用asyncawait 来确保函数等到它完成运行后再进行断言。

我没有使用 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)
})

【讨论】:

    【解决方案2】:

    这就是我最终模拟它的方式。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];
                }
            });
    

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 2020-04-22
      • 2018-05-29
      相关资源
      最近更新 更多