【问题标题】:Cannot read property 'getters' of undefined - VueJS unit testing with jest无法读取未定义的属性“getters” - 带有笑话的 VueJS 单元测试
【发布时间】:2018-12-31 04:17:04
【问题描述】:

我正在为 VueJS 组件编写单元测试,并参考了 Vue Test Utils Common Tips 的“应用全局插件和 Mixins”部分。我有一个依赖于 Vuex 存储的组件,因此出于我的目的,我将转置该部分下的示例是有道理的。

这是该组件的特定 .spec.js 文件的代码:

import { createLocalVue, mount } from '@vue/test-utils'
import AppFooter from '@/components/AppFooter/AppFooter'
import store from '@/store'

describe('AppFooter component', () => {
    const localVue = createLocalVue()
    localVue.use(store)

    it('AppFooter should have header slot', () => {
        const AppFooterComponent = mount(AppFooter, {
            localVue
        })

        /* TODO: Replace with a more appropriate assertion */
        expect(true).toEqual(true)
    })
})

这非常忠实于上面链接中提供的示例。但是,我在运行测试套件时收到的错误如下:

我应该以不同的方式安装 Vue 商店吗?

【问题讨论】:

  • 我相信你应该这样做:localVue.use(Vuex) 在顶部,然后在 localVue 之后将 store 作为参数传递给 mount()。

标签: unit-testing vue.js vuejs2 jestjs vuex


【解决方案1】:

为了详细说明我的评论,我相信它应该如下所示,您在 mount() 调用中传入 store。

import { createLocalVue, mount } from '@vue/test-utils'
import AppFooter from '@/components/AppFooter/AppFooter'
import Vuex from 'vuex'
import store from '@/store' //you could also mock this out.

describe('AppFooter component', () => {
    const localVue = createLocalVue()
    localVue.use(Vuex)

    it('AppFooter should have header slot', () => {
        const AppFooterComponent = mount(AppFooter, {
            store,
            localVue
        })

        /* TODO: Replace with a more appropriate assertion */
        expect(true).toEqual(true)
    })
})

【讨论】:

  • 那没有帮助
【解决方案2】:

我相信您的组件中有类似 this.$store.getters[someBeautifulGetterName] 的东西。要使您的测试挂载组件,您需要初始化存储并将其传递给您的测试组件。请记住,这将是一个全新的 Vuex 实例。这是代码

import { shallowMount } from '@vue/test-utils'
import Vue from 'vue'
import Vuex from 'vuex'
import Tags from '@/components/Tags'
    
Vue.use(Vuex)
Vue.prototype.$store = new Vuex.Store()

const factory = (propsData) => {
  return shallowMount(Tags, {
    propsData: {
      ...propsData
    }
  })
}

describe('Tags', () => {  
  it("render tags with passed data", () => {
    const wrapper = factory({ loading: true })
    // TODO:
  })
})

【讨论】:

    猜你喜欢
    • 2019-07-05
    • 2022-11-24
    • 2019-09-01
    • 2017-06-27
    • 2021-02-06
    • 2019-06-28
    • 2018-10-29
    • 1970-01-01
    • 2020-07-17
    相关资源
    最近更新 更多