如何使用具有存储调度功能的vue-test-utils和jest为组件中的Vue方法编写Vue测试用例

How to write Vue test cases for Vue method in a component using vue-test-utils and jest which has store dispatch function

我正在为我的 vue 组件编写有趣的测试用例 我有一个调用商店调度功能的方法

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

在测试用例中,我触发了如下所示的取消事件,并期望存储操作方法调用

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

但是被驳回的方法调用 "wrapper.vm.dismissed();" 在 运行 测试用例

时抛出以下错误

无法读取未定义的 属性'dispatch'

我如何测试这个 vue 方法?

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

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