🎯 7.2 Vuex の dispatch / commit を含む例

(Vue 2.7 クラスコンポーネント → Composition API 書き換え実例)


✅ 【要点】

→ 型安全も強化でき、Vue 3 以降もそのまま使える形になる。


🟢 【移行前(クラスコンポーネント)】

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

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';

@Component
export default class Counter extends Vue {
  increment(): void {
    this.$store.dispatch('increment');
  }
}
</script>


🟠 【移行後(Composition API)】

<!-- 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>


🟣 【テスト書き換え例】

🎯 クラス時のテスト(Before)

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 (クラス)', () => {
  it('dispatch が呼ばれる', async () => {
    const actions = { increment: jest.fn() };
    const store = new Vuex.Store({ actions });

    const wrapper = shallowMount(Counter, { store, localVue });
    await wrapper.find('button').trigger('click');
    expect(actions.increment).toHaveBeenCalled();
  });
});


✅ Composition API 書き換え後のテスト

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

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

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

describe('Counter.vue (Composition API)', () => {
  beforeEach(() => {
    dispatchMock.mockClear();
  });

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