🎯 4.2 Composition API での useStore のモック方法


✅ 【要点】

Composition API で Vuex を使うと

const store = useStore();
store.dispatch('アクション名');

useStore() をモックして、 dispatch, commit, state, getters などを監視できる

→ クラスコンポーネント時の store: new Vuex.Store(...) の代わりになる。


🟢 【基本のモック方法】

// useStore を Jest でモックする
jest.mock('vuex', () => ({
  useStore: () => ({
    dispatch: jest.fn(),                // ← dispatch をモック
    commit: jest.fn(),                  // ← commit をモック(必要なら)
    state: { count: 0 },                // ← state のモック
    getters: { doubleCount: 0 },        // ← getter のモック
  }),
}));

useStore を呼び出したら、モックしたオブジェクトが返るようになる。


🟠 【具体例: dispatch のテスト】

<!-- Counter.vue -->
<template>
  <button @click="increment">+</button>
</template>

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

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


🧪 テストコード

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

// ここでモックする
const dispatchMock = jest.fn();

jest.mock('vuex', () => ({
  useStore: () => ({
    dispatch: dispatchMock,           // ← モック関数を差し込む
  }),
}));

describe('Counter.vue (Composition API)', () => {
  beforeEach(() => {
    dispatchMock.mockClear();        // ← 毎回クリア
  });

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


🟡 【state / getters もモックするパターン】

const mockState = { count: 5 };
const mockGetters = { doubleCount: 10 };

jest.mock('vuex', () => ({
  useStore: () => ({
    dispatch: jest.fn(),
    commit: jest.fn(),
    state: mockState,
    getters: mockGetters,
  }),
}));