如何使用Vue + Jest模拟axios帖子

时间:2019-06-07 13:38:36

标签: vue.js jestjs axios

我正在尝试通过Jest在Vue中测试一种方法,并且我必须在此方法中测试Axios请求。

我已经搜索了几种解决方案,但是没有找到与我的方案匹配的解决方案,即使我使用过moxios和其他npm软件包,也无法测试此请求

// config.vue
methods: {
    async config () {
      await axios.post('/users/config')
        .then(res => {
          if (res.data.success) {
            M.toast({html: res.data.message, classes: 'green'})
            this.$router.push('/tour')
          }
        })
        .catch(() => {
          M.toast({html: 'Não foi possível contactar, ou você não possui permissão!', classes: 'red'})
        })
    }
  }
```js
// config.spec.js

import { mount, createLocalVue } from '@vue/test-utils'
import config from '@/components/config'
import axios from '@/axios-auth'
jest.mock('axios')

const localVue = createLocalVue()


describe('config', () => {
  const spy = jest.fn()

  it('mocking axios request', () => {
    const wrapper = mount(config, {
      localVue
    })
    wrapper.vm.config()
    expect(spy).toHaveBeenCalledWith('/users/config', 'post', {success: true, message: 'Configuração realizada!'})
  })
})

0 个答案:

没有答案
相关问题