Currently, I am attempting to utilize Jest for testing a Vue component that relies on a getter in Vuex. The getter is structured to return a function that ultimately provides an array:
questions: state => pageNumber => state.pages[pageNumber].questions
Within my component, I incorporate it in the following manner:
computed: {
inputs() {
return this.$store.getters.questions(this.pageNumber);
},
},
Although this approach successfully renders the UI, I encounter an issue when trying to test the component and receive a
Cannot read property 'questions' of undefined
error.
My testing method is relatively simple, but since I am unfamiliar with using Jest alongside Vuex, I may be misunderstanding the process of testing components that rely on getters:
import Vuex from 'vuex';
import { mount, createLocalVue } from '@vue/test-utils';
import SurveyQuestionBuilder from '../components/SurveyQuestionBuilder.vue';
import store from '../store';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('SurveyQuestionBuilder.vue', () => {
it('renders a value from $store.state', () => {
const wrapper = mount(SurveyQuestionBuilder, { store, localVue });
expect(wrapper.exists()).toBeTruthy();
});
});
The issue seems to revolve around pages[pageNumber]
within the getter, and I am uncertain how to address it.
Within Store.js, a few modules are imported:
import Vue from 'vue';
import Vuex from 'vuex';
import surveyBuilderStore from './survey_builder';
import matrixStore from './matrix';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
survey: surveyBuilderStore,
matrix: matrixStore,
},
});
The specific module causing the trouble is surveyBuilderStore:
const surveyBuilderStore = {
state: {
pages: [],
},
getters: {
pages: state => state.pages,
questions: state => pageNumber => state.pages[pageNumber].questions,
config: state => (pageNumber, questionNumber) =>
state.pages[pageNumber].questions[questionNumber].config,
},
mutations: {
// my mutations
}
};