Vuex + Jest + Composition API: How to check if an action has been called

Viewed 383

I am working on a project built on Vue3 and composition API and writing test cases.

The component I want to test is like below.

Home.vue

<template>
  <div>
    <Child @onChangeValue="onChangeValue" />
  </div>
</template>

<script lang="ts>
...

const onChangeValue = (value: string) => {
  store.dispatch("changeValueAction", {
    value: value,
  });
};
</scirpt>

Now I want to test if changeValueAction has been called.

Home.spec.ts

...

import { key, store } from '@/store';

describe("Test Home component", () => {
  const wrapper = mount(Home, {
    global: {
      plugins: [[store, key]],
    },
  });

  it("Test onChangeValue", () => {
    const child = wrapper.findComponent(Child);

    child.vm.$emit("onChangeValue", "Hello, world");
    
    // I want to check changeValueAction has been called.
    expect(wrapper.vm.store.state.moduleA.value).toBe("Hello, world");
  });
});

I can confirm the state has actually been updated successfully in the test case above but I am wondering how I can mock action and check if it has been called.

How can I do it?

1 Answers

I have sort of a similar setup.

I don't want to test the actual store just that the method within the component is calling dispatch with a certain value.

This is what I've done.

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);
    });

This is the Component method:

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

        return {
            removeFavorite
        }
      }

Hope this will help you further :)

Related