如何在Jest中测试VueJS(Nuxt)Store,解决easg_logo未定义报错
问题原因
- Vuex 构造配置错误:你错误地将根state放到了
modules配置项中,导致实际挂载到Store上的state路径为$store.state.state.app,和组件中访问的$store.state.app路径不匹配,所以读取easg_logo时会报undefined。 - 组件语法错误:
data函数没有返回对象,且重复定义了oma_logo_width、缺失了oma_logo_height属性,运行时也会触发异常。
修正方案
1. 先修正footer.vue的语法问题
<template> <div> <v-img :height="easg_logo_height" :src="$store.state.app.easg_logo.src" :width="easg_logo_width" contain /> <v-img :height="oma_logo_height" :src="$store.state.app.oma_logo.src" :width="oma_logo_width" contain /> </div> </template> <script> export default { data(){ return { easg_logo_width: this.$store.state.app.easg_logo.top.width, easg_logo_height: this.$store.state.app.easg_logo.top.height, oma_logo_width: this.$store.state.app.oma_logo.top.width, oma_logo_height: this.$store.state.app.oma_logo.top.height, } } } </script>
2. 修正测试代码中的Store初始化逻辑
如果你是直接使用根state存储app数据,直接把state传入Store配置即可:
import {shallowMount, createLocalVue} from '@vue/test-utils' import Vuex from 'vuex'; import Footer from '@components/layouts/default/footer' import Vuetify from 'vuetify'; const vuetify = new Vuetify(); const localVue = createLocalVue(); localVue.use(Vuex); describe("Footer tests", ()=> { let wrapper; let store; let state; beforeEach(() => { state= { app: { easg_logo:{ src: "~/assets/images/easg.jpg", text: "EASG", top:{ height: 72, width: 82 } }, oma_logo:{ src: "~/assets/images/oma.jpg", text: "OMA", top:{ height: 72, width: 82 } } } } // 直接传state,不需要套modules store = new Vuex.Store({ state }) }) test('store test', ()=> { wrapper = shallowMount(Footer, {store, localVue, vuetify}) // 可以加实际业务断言验证 expect(wrapper.vm.easg_logo_width).toBe(82) }); });
如果你的实际项目中app是单独的Vuex模块,就按模块写法初始化:
// beforeEach内替换Store初始化逻辑 const appModule = { state: { easg_logo:{ src: "~/assets/images/easg.jpg", text: "EASG", top:{ height: 72, width: 82 } }, oma_logo:{ src: "~/assets/images/oma.jpg", text: "OMA", top:{ height: 72, width: 82 } } } } store = new Vuex.Store({ modules: { app: appModule } })
内容的提问来源于stack exchange,提问作者Jamie
相关产品推荐
相关产品推荐

