Vuexの**storeモジュール(state / mutations / actions / getters)**は、
コンポーネントを使わずに直接テストできる。
→
mutation
→ 関数を直接呼び出して state
が変わるかチェックaction
→ 非同期なら async/await
で確認getter
→ 関数を直接呼んで結果を確認// src/store/modules/counter.ts
import { ActionContext } from 'vuex';
// state の型
export interface CounterState {
count: number;
}
// state 本体
export const state = (): CounterState => ({
count: 0,
});
// mutation
export const mutations = {
increment(state: CounterState): void {
state.count += 1;
},
};
// action
export const actions = {
async incrementAsync({ commit }: ActionContext<CounterState, unknown>): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 1000));
commit('increment');
},
};
// getter
export const getters = {
doubleCount(state: CounterState): number {
return state.count * 2;
},
};
// tests/store/counter.mutations.spec.ts
import { mutations } from '@/store/modules/counter';
describe('counter mutations', () => {
it('increment は count を1増やす', () => {
const state = { count: 0 };
mutations.increment(state);
expect(state.count).toBe(1); // 1増えていることを確認
});
});
// tests/store/counter.getters.spec.ts
import { getters } from '@/store/modules/counter';
describe('counter getters', () => {
it('doubleCount は count を2倍にする', () => {
const state = { count: 5 };
const result = getters.doubleCount(state);
expect(result).toBe(10); // 5 x 2 = 10
});
});