【问题标题】:Vue test utils not recognising $http in the testsVue 测试工具在测试中无法识别 $http
【发布时间】:2018-11-04 19:47:39
【问题描述】:

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

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

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

【问题讨论】:

    标签: vue.js axios jestjs vue-test-utils


    【解决方案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 ...
    })
    

    【讨论】:

    • 感谢乔治的回复。我已经按照上面的做了。不幸的是,我在运行测试时仍然得到TypeError: Cannot read property 'get' of undefined
    猜你喜欢
    • 2012-11-21
    • 2019-03-30
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2021-06-17
    • 2013-04-14
    相关资源
    最近更新 更多