this.$store.dispatch
→ useStore().dispatch
への書き換え(Vuex を使う Composition API 化とテストの書き換え)
クラスコンポーネントでは Vuex の操作を
this.$store.dispatch('アクション名')
Composition API に書き換えると
const store = useStore();
store.dispatch('アクション名');
👉 Vuex ストアへのアクセス方法が完全に変わる。
👉 Jest のテストでは useStore()
をモックする必要がある。
<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>
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('increment action を dispatch する', () => {
const actions = { increment: jest.fn() };
const store = new Vuex.Store({ actions });
const wrapper = shallowMount(Counter, {
store,
localVue,
});
wrapper.find('button').trigger('click');
expect(actions.increment).toHaveBeenCalled();
});
});
<template>
<button @click="increment">+</button>
</template>
<script lang="ts" setup>
import { useStore } from 'vuex';
const store = useStore();
const increment = () => {
store.dispatch('increment');
};
</script>