🎯 5.3 モックストアの作り方と使い方


✅ 【要点】

→ コンポーネントからの Vuex 利用を簡単にテストできる。


🏗️ 【基本のモックストア作成】

// storeをモックする
const actions = {
  increment: jest.fn(),              // actionをモック
};

const getters = {
  doubleCount: () => 4,              // getterをモック
};

const state = {
  count: 2,                          // stateの初期値
};

// Vuexストアを作成(必要な部分だけ)
const store = new Vuex.Store({
  state,
  getters,
  actions,
});

これで「本物のロジックなし」で、

state.countgetters.doubleCount が使えるストア ができる。


🟢 【コンポーネントと一緒に使う】

// Counter.vue のテスト
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import Counter from '@/components/Counter.vue';

const localVue = createLocalVue();
localVue.use(Vuex);

describe('Counter.vue with mock store', () => {
  it('getter の doubleCount が正しく表示される', () => {
    const getters = {
      doubleCount: () => 10,                  // getterをモック
    };

    const store = new Vuex.Store({
      state: { count: 5 },                    // stateは5
      getters,
      actions: { increment: jest.fn() },     // actionもモック
    });

    const wrapper = shallowMount(Counter, {
      store,
      localVue,
    });

    expect(wrapper.vm.count).toBe(5);         // state.count の確認
    expect(store.getters.doubleCount).toBe(10); // getterの確認
  });
});


🔥 【action の呼び出しをモックするパターン】

it('increment action が呼ばれる', () => {
  const actions = { increment: jest.fn() };
  const store = new Vuex.Store({
    state: { count: 0 },
    actions,
  });

  const wrapper = shallowMount(Counter, {
    store,
    localVue,
  });

  wrapper.find('button').trigger('click');
  expect(actions.increment).toHaveBeenCalled();
});