使用Jest测试Vue3组件时如何mock计算属性而无需完整模拟Vuex store
解决方案
方案1:最小化mock用到的Vuex getter(推荐)
你不需要完整mock整个Vuex store,只需要mock当前用到的单个getter即可,代码量极少,完全没有冗余:
import { mount } from '@vue/test-utils'; import WelcomeMessage from '@/components/WelcomeMessage.vue'; describe('WelcomeMessage.vue', () => { it('should display the message', () => { const wrapper = mount(WelcomeMessage, { global: { mocks: { // 仅mock用到的$store属性,其余内容无需处理 $store: { getters: { neverShowWelcomeMessageAgain: false } } } } }); expect(wrapper.text()).toContain('Welcome'); }); });
这个方案的优势是不用修改组件本身的逻辑,贴合实际运行场景,仅需一行额外的mock代码就能满足需求。
方案2:直接覆盖组件的计算属性
如果你完全不想碰任何Vuex相关的mock,也可以直接替换组件本身的计算属性实现:
import { mount } from '@vue/test-utils'; import WelcomeMessage from '@/components/WelcomeMessage.vue'; describe('WelcomeMessage.vue', () => { it('should display the message', () => { // 用jest.spyOn覆盖计算属性的返回值,测试结束后可自动恢复避免影响其他用例 const computedSpy = jest.spyOn(WelcomeMessage.computed, 'isNeverShowAgain') .mockReturnValue(false); const wrapper = mount(WelcomeMessage); expect(wrapper.text()).toContain('Welcome'); // 恢复原计算属性实现 computedSpy.mockRestore(); }); });
原代码报错原因说明
Vue Test Utils v2已经移除了mount配置中的computed选项,你传入的自定义computed没有生效,组件依然会执行原有的计算属性逻辑读取$store,因此抛出了store未定义的错误。
内容的提问来源于stack exchange,提问作者Marcel
相关产品推荐
相关产品推荐

