Vue-test-utils:如何模拟 VueX 中某个动作的 return?

Vue-test-utils: How do I mock the return of an action in VueX?

我正在为 Vue 组件编写一个测试,该组件分派到模块存储以执行操作并使用它的结果。

该操作调用了我们的 API,所以我不想 运行 使用该操作进行测试,而是模拟它和 return 一些虚拟数据以供查看方法流程的其余部分有效。

因此,在我的测试中,我添加了一个模拟商店,其中包含一个模拟操作,该操作只是 returns 硬编码数据,目的是查看组件方法 getData() 将操作的响应设置为数据.

然而,这似乎不起作用,而是似乎调用了真正的操作。我该如何设置才能避免调用实际操作,而是使用我为测试创建的操作?

组件方法,简化:

methods: {
    async getData() {
        const response = this.$store.dispatch("global/getDataFromAPI")

        if (!response) return

        this.$data.data = {...response.data}
    }
}

测试代码,简化:

describe('Component.vue', () => {
  let localVue;
  let vuetify;
  let wrapper;
  let store;

  beforeEach(() => {
    localVue = createLocalVue();
    localVue.use(Vuex)
    vuetify = new Vuetify();

    let globalActions = {
      getDataFromAPI: async () => {
        return {
          status: 200,
          data: {
            information1: "ABC",
            information2: 123,
          }
        }
      } 
    }

    store = new Vuex.Store({
      modules: {
        global: {
          actions: globalActions,
          namespaced: false
        },
      }
    })

    wrapper = mount(Component, {
      localVue,
      vuetify,
      attachTo: div,
      mocks: {
        $t: () => { },
        $store: store,
      },
    });
  });

  it('Data is set correctly', async () => {
    await wrapper.vm.getData();

    const dataInformation1 = wrapper.vm.$data.data.information1;
    expect(dataInformation1).toBe("ABC")
  });

首先,如果你想模拟Vuex Store你不需要调用localVue.use(Vuex)。仅当您要在测试中使用真实的 Vuex Store 时才应调用 localVue.use(Vuex)。如果你要去你必须传递 store 对象连同 localVue 和另一个参数,而不是 mocks 属性.

第二个,要模拟你的动作,你可以像这样模拟storedispatch方法:

mocks: {
  $store: {
    dispatch: () => { dummyData: 'dummyData' }
  }
}