You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 01:00:04