【问题标题】:Component can't access action defined in test store (Vue Test Utils)组件无法访问测试商店中定义的操作(Vue Test Utils)
【发布时间】:2021-05-07 19:14:43
【问题描述】:

按照Vue Test Utilsdocs,我在我的测试中创建了一个测试商店(复制我的真实商店):

里面有这个动作:

actions: {
  updatePowerSelectedAction(
    { commit }: ActionContext<State, RootState>,
    val: number
  ) {
    commit('UPDATE_POWER_SELECTED', val);
  },
},

...当一个按钮被点击时被测试的组件调用:

模板:

<button v-for="(power, i) in powers" :key="i" @click="comparePower(power)" />

JS:

function comparePower(val: string) {
  updatePowerSelectedAction(val);
  ...
}

我可以看到该组件已正确加载,但是当通过await wrapper.findAll('.button')[0].trigger('click'); 单击按钮时,它无法调用该操作。

没有错误消息,只是没有调用该操作。为什么不呢?

【问题讨论】:

    标签: vue.js vuejs3 vue-test-utils


    【解决方案1】:

    在您的 BattlePowers 中添加一个名为 powerbutton 的类,以使该按钮独一无二:

      <button
        v-for="(power, i) in powers" :key="i" 
        @click="comparePower(power)"
        class="button powerbutton"
      >
        {{ power }}
      </button>
    

    然后在测试文件battle-powers.spec.ts 中导入全局存储,而不是在测试文件中创建新存储,因为当您模拟按钮单击时,此全局存储将受到影响:

    import { shallowMount } from '@vue/test-utils';
    import BattlePowers from '@/views/battle/battle-powers.vue';
    import store from '@/store'
    
    describe('BattlePowers', () => {
      it('updates store variable powerSelected with power clicked by user', async () => {
        const wrapper = shallowMount(BattlePowers, {});
        await wrapper.findAll('.powerbutton')[1].trigger('click');
        expect(store.getters['powerSelected']).toBe("strength");
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2019-07-16
      • 1970-01-01
      • 2021-02-17
      • 2018-12-05
      • 2021-04-03
      • 2019-10-24
      • 2021-06-12
      • 1970-01-01
      • 2019-04-17
      相关资源
      最近更新 更多