【问题标题】:How to wait for request to be finished with axios-mock-adapter like it's possible with moxios?如何等待使用 axios-mock-adapter 完成请求,就像使用 moxios 一样?
【发布时间】:2019-03-31 05:59:20
【问题描述】:

我尝试在从服务器获取某些内容后测试其渲染。 我使用Vue Test Utils,但这无关紧要。

在组件的created 钩子中,使用axios 进行ajax 调用。我注册了axios-mock-adapter 响应并“渲染”组件,进行了调用,一切正常,但我必须使用moxios 库来等待请求完成。

it('displays metrics', (done) => {

  this.mock.onGet('/pl/metrics').reply((config) => {
    let value = 0
    if (config.params.start == '2020-01-26') {
      value = 80
    }
    if (config.params.start == '2020-01-28') {
      value = 100
    }
    return [200, {
      metrics: [
        {
          key: "i18n-key",
          type: "count",
          value: value
        }
      ]
    }]
  })
  .onAny().reply(404)

  let wrapper = mount(Dashboard)

  moxios.wait(function() {
    let text = wrapper.text()
    expect(text).toContain('80')
    expect(text).toContain('100')
    expect(text).toContain('+20')
    done()
  })
})

是否有可能摆脱 moxios 并仅使用 axios-mock-adapter 实现相同的效果?

【问题讨论】:

    标签: jasmine moxios axios-mock-adapter


    【解决方案1】:

    是的,您可以使用 async/await 实现自己的 flushPromises 方法:

    const flushPromises = () => new Promise(resolve => setTimeout(resolve))
    
    it('displays metrics', async () => {
      this.mock.onGet('/pl/metrics').reply((config) => {
        // ..
      }).onAny().reply(404)
    
      let wrapper = mount(Dashboard)
    
      await flushPromises()
    
      expect(text).toContain('80')
    })
    

    或者使用donesetTimeout

    it('displays metrics', (done) => {
      this.mock.onGet('/pl/metrics').reply((config) => {
        // ..
      }).onAny().reply(404)
    
      let wrapper = mount(Dashboard)
    
      setTimeout(() => {
        expect(text).toContain('80')
        done()
      })
    })
    

    moxiois.wait 就是schedules a callback with setTimeout。这是因为 setTimeout 调度的任务总是在微任务队列(如承诺回调)被清空后运行。

    【讨论】:

    • 非常感谢埃德!我会尽快尝试的! :)
    猜你喜欢
    • 1970-01-01
    • 2018-06-13
    • 2020-06-08
    • 2018-11-28
    • 2018-03-17
    • 2018-04-07
    • 2016-09-06
    • 2018-05-29
    • 1970-01-01
    相关资源
    最近更新 更多