(Composition API + Vuex の場合)
Vuex を使う Composition API では、
dispatch
→ action を呼び出すcommit
→ mutation を呼び出すstate
, getters
→ 値を読み出す→ Jest のテストでは これらを「モック」して動作を確認する。
→ クラスコンポーネントとやり方が変わるので注意。
<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>
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 は action 経由で呼ばれる
→ action の単体テスト内で
commit
のモックを使って確認する。