使用Jest测试Vuex Getter时返回undefined的问题排查
解决Jest测试Vuex Getter返回undefined的问题
我帮你排查了几个核心问题,咱们一步步来修复:
1. 组件计算属性遗漏返回值
首先看你的update.vue里的updatedValue计算属性——你只是定义了变量,但没有return获取到的store getter值,这直接导致组件里的这个计算属性始终返回undefined,不管getter本身是否正常工作。
修正后的组件代码:
<template> <div class="updateCss"> <customList :items="updatedValue"></customList> </div> </template> <script> import types from '@/store/types' export default class UpdateTest extends Vue { get updatedValue() { // 关键:加上return语句 return this.$store.getters[types.GET_UPDATE_VALUE]; } } </script>
2. 测试用例中Mock的Store配置错误
你的update.spec.ts里有两个关键问题:
- Mock的getter键名和实际项目中使用的不匹配(你用了
updatedValue,但实际是types.GET_UPDATE_VALUE对应的键) - 使用
jest.fn()但没有设置返回值,默认会返回undefined
修正后的测试代码:
import Vuex from 'vuex' import { createLocalVue, shallowMount } from '@vue/test-utils' import UpdateTest from '@/components/update.vue' import types from '@/store/types' const localVue = createLocalVue() localVue.use(Vuex) describe('Update Component TestSuite', () => { let store let updateWrapper beforeEach(() => { store = new Vuex.Store({ modules: { // 确保模块名称和实际store中注册的名称完全一致 storeConfigurations: { state: { update: false }, getters: { // 使用项目中实际的getter键名(types里的常量) [types.GET_UPDATE_VALUE]: () => false // 或者用jest mock并指定返回值: // [types.GET_UPDATE_VALUE]: jest.fn().mockReturnValue(false) } } } }) updateWrapper = shallowMount(UpdateTest, { store, localVue }) }) // 添加测试用例验证结果 test('should retrieve correct value from Vuex getter', () => { expect(updateWrapper.vm.updatedValue).toBe(false) }) })
3. 额外注意:命名空间(如果开启的话)
如果你的storeConfigurations模块设置了namespaced: true,那组件里调用getter时需要加上模块前缀,测试里的mock也要对应调整:
- 组件里的调用改为:
return this.$store.getters['storeConfigurations/' + types.GET_UPDATE_VALUE] - 测试里的getter键名保持
[types.GET_UPDATE_VALUE]即可,因为模块内部的getter键名不需要前缀
总结
导致问题的核心原因:
- 组件计算属性未return值
- 测试中mock的getter键名不匹配且无返回值
- (可选)命名空间配置不一致
按上面的步骤修正后,你的测试应该能正确获取到getter的值了。
内容的提问来源于stack exchange,提问作者Sapthika
相关产品推荐
相关产品推荐

