【问题标题】:How to write Vue test cases for Vue method in a component using vue-test-utils and jest which has store dispatch function如何使用具有存储调度功能的 vue-test-utils 和 jest 在组件中为 Vue 方法编写 Vue 测试用例
【发布时间】:2020-06-14 21:21:06
【问题描述】:

我正在为我的 vue 组件编写开玩笑的测试用例 我有一个调用存储调度函数的方法

dismissed() {
      this.$store.dispatch("alert/hideAlert");
},

在测试用例中,我触发了如下所示的已关闭事件,并期望调用 store 操作方法

 wrapper.vm.dismissed();
 await wrapper.vm.$nextTick();
 expect(actions.hideAlert).toHaveBeenCalled();

但被解雇的方法调用“wrapper.vm.dismissed();”运行测试用例时抛出以下错误

无法读取未定义的属性“dispatch”

如何测试这个 vue 方法?

【问题讨论】:

    标签: vue.js jestjs vue-component vuex vue-test-utils


    【解决方案1】:

    我认为这是最简单的方法。

    const mockStore = { dispatch: jest.fn() }
    const wrapper = shallowMount(YourComponent, {
       mocks: {
          $store: mockStore
       }
    }
    
    wrapper.vm.dismissed();
    await wrapper.vm.$nextTick();
    expect(mockStore.dispatch).toHaveBeenCalledWith('alert/hideAlert');
    

    但你也可以用不同的方式来做。 Check this article

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 2018-09-28
      • 2019-02-10
      • 2021-09-11
      • 2019-07-16
      • 2019-10-24
      • 2019-01-25
      • 2018-08-06
      • 2019-05-28
      相关资源
      最近更新 更多