4

I try to test a rendering of some content after fetching it from server. I use Vue Test Utils but this is irrelevant.

In the created hook of the component the ajax call is made with axios. I register the axios-mock-adapter response and 'render' the component, the call is made and everything works fine but i have to use the moxios lib only to wait for request to be finished.

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()
  })
})

Is it possible to get rid of moxios and achieve the same with axios-mock-adapter only?

Paul Geisler
  • 695
  • 1
  • 5
  • 23

1 Answers1

3

Yes, you can implement your own flushPromises method with async/ await:

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')
})

Or use done and setTimeout:

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 simply schedules a callback with setTimeout. This works because a task scheduled by setTimeout always runs after the microtask queue, like promise callbacks, is emptied.

Edd
  • 4,036
  • 1
  • 24
  • 40