I'm trying to test different parts of VueX store. I keep mutations, getters and else in single file (index.js) but somehow it does not work when import that file into test file. Here is my VueX: Vue.use(Vuex);
Index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
pickedDates:[]
},
mutations: {
mutatePickedDates: (state, payload) => {
state.pickedDates = payload;
},
})
Now in Store.spec.js
I want to test it:
import storeConfig from '@/store/index.js'
const store = storeConfig
test('check if state is working', () =>{
const state = {
pickedDates: []
}
const dates = ['1995-01-01', '1995-01-01']
store.mutations.mutatePickedDates(state, {dates})
expect(state.pickedDates).toBe(dates)
})
But I get error: TypeError: Cannot read property 'mutatePickedDates' of undefined
when running test.
There are two approaches to testing vuex. First one is to unit test actions, mutations and getters. Second is to test working store directly.
If you want to test stores mutations isolated from components, I would recommend exporting them.
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const mutations = {
mutatePickedDates: (state, payload) => {
state.pickedDates = payload;
}
};
export default new Vuex.Store({
state: {
pickedDates:[]
},
mutations: mutations
})
Then you can import and test mutations directly.
import { mutations } from '@/store/index.js'
test('check if state is working', () =>{
const state = {
pickedDates: []
}
const dates = ['1995-01-01', '1995-01-01']
mutations.mutatePickedDates(state, dates)
expect(state.pickedDates.length).toBe(2)
})
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import store from '@/store/index.js'
test('check if state is working', () =>{
// initial state
const state = {
pickedDates: []
}
const dates = ['1995-01-01', '1995-01-01']
// create local instance and vuex store
const localVue = createLocalVue()
localVue.use(Vuex)
// commit mutation
store.commit('mutatePickedDates', dates)
expect(store.pickedDates.length).toBe(2)
})