1

有一个带有 axios 设置的 Vue 应用程序,并且this.$http.get在组件中使用它,并且工作正常。

在使用 Jest 运行规范时,出现错误:Cannot read property 'get' of undefined

我知道我可以用 maxios 模拟 axios。如何让 Jest 识别 $http 使其不会引发错误?

4

1 回答 1

1

您需要为您的测试创建一个本地 Vue 实例,向其中介绍您正在使用的 Vue 插件,例如 axios。

import { createLocalVue, shallowMount } from "@vue/test-utils"
import axios from 'axios'
import VueAxios from 'vue-axios'


const localVue = createLocalVue();
localVue.use(VueAxios, axios)

后来,在您的实际测试中:

it('should mount the component where I want to use $http', () => {
    const wrapper = shallowMount(MyApiComponent, { localVue });
    ... do stuff to wrapper here ...
})
于 2018-05-25T13:36:22.580 回答