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

VueJS+Jest测试局部引入mixin的组件时Vuex action未触发如何解决

测试携带局部引入mixin的组件不需要将mixin全局引入后再mock,你遇到的问题是代码写法错误导致的,和mixin是否全局引入无关。

错误点说明

  1. Vuex实例初始化结构错误
    Vuex 构造函数要求根状态必须声明在state配置项下,你原代码中直接把selected放在了Store的根配置里,导致mixin中mapState读取state.selected.config返回undefined,updateConfig方法执行时读取this.config直接报错中断,后续的action自然不会被调用。
  2. 组件输入触发方式错误
    你直接操作原生DOM修改value触发input事件的方式,对Buefy封装的b-input组件不生效,无法正确触发组件绑定的@input回调updateConfig。应该使用Vue Test Utils提供的setValue方法来操作组件输入。

修改后可正常运行的测试代码

import { mount, createLocalVue } from '@vue/test-utils';
import JavaOptions from '@/components/partials/java_settings/javaoptions.vue';
import Buefy from 'buefy';
import Vuex from 'vuex';

const localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(Buefy);

describe('JavaOptions.vue', () => {
  let actions;
  let store;
  beforeEach(() => {
    actions = {
      updateServerConfigAction: jest.fn(),
    };
    // 修正store结构,将状态放到state字段下
    store = new Vuex.Store({
      state: {
        selected: { config: { java_xmx: '' } }
      },
      actions,
    });
  });

  it("expect 'updateServerConfigAction' to be called on setting change", async () => {
    const wrapper = mount(JavaOptions, {
      store,
      localVue,
    });
    const java_xmx = wrapper.find('#java_xmx');
    // 使用setValue方法触发组件输入,自动处理事件触发和状态更新
    await java_xmx.setValue(235);
    expect(java_xmx.element.value).toBe('235');
    // 验证mock的action被调用
    expect(actions.updateServerConfigAction).toHaveBeenCalled();
  });
});

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:24:03