🎯 4.3 action / mutation / getter のテストパターン整理

(Composition API + Vuex の場合)


✅ 【要点】

Vuex を使う Composition API では、

→ Jest のテストでは これらを「モック」して動作を確認する

クラスコンポーネントとやり方が変わるので注意。


🟢 【基本形:Vuex を使う Composition API】

<template>
  <p>{{ doubleCount }}</p>
  <button @click="increment">+</button>
</template>

<script lang="ts" setup>
import { useStore } from 'vuex';
import { computed } from 'vue';

const store = useStore();

const doubleCount = computed(() => store.getters.doubleCount);
const increment = () => {
  store.dispatch('increment');
};
</script>


🟠 【action のテストパターン】

✅ 1. dispatch が呼ばれているか?

import { shallowMount } from '@vue/test-utils';
import Counter from '@/components/Counter.vue';

// dispatch モック
const dispatchMock = jest.fn();

jest.mock('vuex', () => ({
  useStore: () => ({
    dispatch: dispatchMock,
    getters: { doubleCount: 0 },
  }),
}));

describe('Counter.vue (action のテスト)', () => {
  beforeEach(() => {
    dispatchMock.mockClear();
  });

  it('ボタンをクリックすると increment action が dispatch される', async () => {
    const wrapper = shallowMount(Counter);
    await wrapper.find('button').trigger('click');
    expect(dispatchMock).toHaveBeenCalledWith('increment');
  });
});


🟡 【mutation のテストパターン】

通常、mutation は action 経由で呼ばれる

→ action の単体テスト内で commit のモックを使って確認する。