我正在为 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 商店吗?
为了详细说明我的评论,我相信它应该如下所示,您在 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)
})
})
我相信你的组件中有类似这样的东西。$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:
})
})