如何在Jest中测试Vue组件内Vuex Mutation的调用
Vue组件调用Vuex接口的Jest测试方案
前置配置
先在jest.config.js中添加如下配置,实现mock自动还原,避免测试用例互相影响:
module.exports = { // 其他原有配置 resetMocks: true, // Vue3环境需要额外添加该行配置 testEnvironment: 'jsdom' }
开启resetMocks后,Jest会在每个测试用例执行完成后自动清空所有mock函数的调用记录、重置mock实现,不需要手动编写清理逻辑。
完整测试实现
步骤1:编写测试代码
以下是针对你的组件的完整测试示例,兼容Vue2/Vue3,同时支持commit、dispatch(对应action)、getters的测试:
import { mount } from '@vue/test-utils' import { createStore } from 'vuex' // Vue2对应导入Vuex,通过new Vuex.Store创建实例 import YourComponent from './YourComponent.vue' // 测试用预设参数 const mockParameter = 'test_val' const mockTransformedParameter = 'transformed_test_val' describe('YourComponent', () => { let wrapper let mockStore beforeEach(() => { // 每次测试前创建全新的mock store,避免用例间状态污染 mockStore = createStore({ mutations: { // 不需要实际实现,仅保留mock即可 storeSomething: jest.fn(), storeSomethingElse: jest.fn() }, // 测试action就添加mock的actions,测试getters就添加mock的getters actions: { someAction: jest.fn() }, getters: { someGetter: () => 'mock_value' } }) // 挂载组件时传入mock store wrapper = mount(YourComponent, { global: { // Vue2此处写mocks,或者在plugins中引入store plugins: [mockStore], // 轻量方案:不需要创建完整store实例,直接mock $store对象即可,测试速度更快 // mocks: { // $store: { // commit: jest.fn(), // dispatch: jest.fn(), // getters: { someGetter: 'mock_value' } // } // } } }) // 可选:mock组件内部的transformToSth方法,隔离外部依赖 jest.spyOn(wrapper.vm, 'transformToSth').mockReturnValue(mockTransformedParameter) }) test("that the commit was correctly called", () => { wrapper.vm.doSomething(mockParameter); // 注意:commit第一个参数是mutation名,第二个才是传参,不要漏写;Jest断言方法为toHaveBeenCalledWith expect(wrapper.vm.$store.commit).toHaveBeenCalledWith("storeSomething", mockParameter); expect(wrapper.vm.$store.commit).toHaveBeenCalledWith("storeSomethingElse", mockTransformedParameter); }) })
步骤2:扩展适配action、getter测试
- 测试action调用:和commit逻辑完全一致,将
commit替换为dispatch,断言dispatch的调用参数即可 - 测试getter依赖:直接在mock的getters对象中定义对应返回值,组件内调用
this.$store.getters.xxx时会自动读取mock值,也可以用jest.fn()实现动态返回不同值的测试需求
内容的提问来源于stack exchange,提问作者telion
相关产品推荐
相关产品推荐

