jest mock vuex useStore() with vue 3 composition api

jest mock vuex useStore() with vue 3 composition api

我正在尝试对一个组件进行单元测试,您可以在其中单击一个按钮,然后该按钮会调用 store.dispatch('favoritesState/deleteFavorite').

此操作然后调用 api 并执行它。我不想测试vuex store的实现,只是想在组件中点击按钮时调用vuex action

组件看起来像这样

<template>
    <ion-item :id="favorite.key">
        <ion-thumbnail class="clickable-item remove-favorite-item" @click="removeFavorite()" slot="end" id="favorite-star-thumbnail">           
        </ion-thumbnail>
    </ion-item>
</template>

import {useStore} from "@/store";
export default defineComponent({
     setup(props) {
        const store = useStore();
    
        function removeFavorite() {
            store.dispatch("favoritesState/deleteFavorite", props.item.id);
        }

        return {
            removeFavorite,
        }
     }
});

笑话测试

import {store} from "@/store";

test(`${index}) Test remove favorite for : ${mockItemObj.kind}`, async () => {

    const wrapper = mount(FavoriteItem, {
        propsData: {
            favorite: mockItemObj
        },
        global: {
            plugins: [store]
        }
    });
    const spyDispatch = jest.spyOn(store, 'dispatch').mockImplementation();

    await wrapper.find('.remove-favorite-item').trigger('click');
    expect(spyDispatch).toHaveBeenCalledTimes(1);
});

我尝试过不同的解决方案,但结果相同。每当“触发器('click')”为 运行 时,它就会抛出此错误:

Cannot read properties of undefined (reading 'dispatch') TypeError: Cannot read properties of undefined (reading 'dispatch')

该项目是使用组合 API 和 vuex4

用打字稿用 vue3 编写的

我找到了解决问题的办法。 这是我最终得到的解决方案。

favorite.spec.ts

import {key} from '@/store';

let storeMock: any;

beforeEach(async () => {
    storeMock = createStore({});
});

test(`Should remove favorite`, async () => {

        const wrapper = mount(Component, {
            propsData: {
                item: mockItemObj
            },
            global: {
                plugins: [[storeMock, key]],
            }
        });
        const spyDispatch = jest.spyOn(storeMock, 'dispatch').mockImplementation();

        await wrapper.find('.remove-favorite-item').trigger('click');
        expect(spyDispatch).toHaveBeenCalledTimes(1);
        expect(spyDispatch).toHaveBeenCalledWith("favoritesState/deleteFavorite", favoriteId);
    });

这是组件方法:

  setup(props) {
    const store = useStore();
   
    function removeFavorite() {
        store.dispatch("favoritesState/deleteFavorite", favoriteId);
    }

    return {
        removeFavorite
    }
  }