state
/ getters
/ actions
/ mutations
だけ用意 して→ コンポーネントからの 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.count
や getters.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の確認
});
});
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();
});