Search code examples
vue.jsunit-testingjestjsvue-test-utils

How to mock axios with Vue Test Utils and Jest?


I'm trying to run example from here: https://v1.test-utils.vuejs.org/guides/#testing-asynchronous-behavior

my component:

<template>
  <button @click="fetchResults">{{ value }}</button>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      value: null,
    }
  },

  methods: {
    async fetchResults() {
      const response = await axios.get('mock/service')
      this.value = response
    },
  },
}
</script>

my test:

import { mount } from '@vue/test-utils'
import flushPromises from 'flush-promises'
import Foo from '@/components/test-axios.vue'

jest.mock('axios', () => ({
  get: Promise.resolve('value'),
}))

it('fetches async when a button is clicked', async () => {
  const wrapper = mount(Foo)
  await wrapper.find('button').trigger('click')
  await flushPromises()
  expect(wrapper.text()).toBe('value')
})

and as result I'm getting error:

TypeError: _axios.default.get is not a function

Please help, what I'm doing wrong?


Solution

  • 'get' should be a function.

    You could wrap the get with a jest.fn to mock the call of get to be able to test it was called.

    jest.mock('axios', () => ({
      get: jest.fn(() => Promise.resolve('value')),
    }))