Issue with Vuex and Jest - Accessing undefined property <getterName>

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
  }
};

Answer №1

When accessing your questions getter, it seems you may be searching at an unknown index in the pages array.

Therefore,

questions: state => pageNumber => state.pages[pageNumber]
is undefined because state.pages is empty and the value of pageNumber is greater than 0.

To prevent this issue, you can make the following adjustment:

questions: state => pageNumber => {
    return state.pages[pageNumber] 
       ? state.pages[pageNumber].questions 
       : [] // <-- your default value can be specified here
}

If you need to set the value of pageNumber in your test, consider whether it is a prop or part of the component's data:

For data:

mount(SurveyQuestionBuilder, { 
    store, 
    localVue, 
    data:() => ({ pageNumber: 0 }) 
})

For props:

mount(SurveyQuestionBuilder, { 
    store, 
    localVue, 
    propsData: { pageNumber: 0 } 
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customize URL based on selected button

My question may be a bit unclear, but I want to generate dynamic URLs that redirect users to specific pages based on the link clicked. For example: Parent page with links (a, b, c, x, y) User clicks on 'b' User is taken to a Node Page that play ...

Determine whether the response from a jQuery AJAX call is in JSON format or binary. If it is found to be binary, proceed

I am currently using ajax to retrieve and download an xlsx file from a PHP script. The script has two possible types of responses: JSON format if there are any warnings preventing the download (such as incorrect parameters), or the xlsx binary stream if ev ...

Update each number in an array by appending a string within a table in an Angular component, rather than the

I have created a function that decides on a comment based on the result number added to an array and displays it in a table. However, calling this function within the template is causing a performance slowdown. Is there a way to achieve the same outcome w ...

What causes the reflection of JavaScript variables when there is a change in ng-model?

By declaring the object globally and assigning it during an HTTP call when the Angular controller loads, I am able to update the values of this object in the Angular scope variables and access them through ng-models. When a button is clicked and one of the ...

Combine words into lowercase in JavaScript variable

I'm struggling to understand why the data from a form field input is not being stored correctly in a SharePoint column data collection. Currently, when someone inputs a name into a form field, it should automatically populate a SharePoint list: http ...

The Node.js engine isn't updating to support compatibility with Firebase functions

Encountered First Failure Below is the content of package.json "engines": { "node": "8.0.0" }, Error: The engines field in the functions directory's package.json is unsupported. You can choose from: {&quo ...

Utilizing jQuery Ajax to retrieve a multitude of data

Utilizing jQuery AJAX to retrieve a string from PHP containing JavaScript, PHP, and HTML has been successful for me using the code below: header("Content-Type: text/html"); echo $content; $.ajax({ type: 'POST', url: url, data: data, ...

Feeling uncertain about Node, NPM, Bower, and how to set them up for Bootstrap?

Looking to expand my knowledge in web development, I have a solid understanding of HTML, JS, CSS, and server-side programming. However, the concepts of Nodejs, npm, and Bower are still unclear to me. In order to begin a new project, I created a designated ...

Working with MySQL in Node.js using async/await

Struggling with utilizing async/await in Node.js with MySQL as it consistently returns an undefined value. Can someone shed light on what could be causing this issue? See my code snippet below. const mysql = require('promise-mysql'); var co ...

Unable to execute main JS template in Angular partial view, JQuery function also fails to work on the partial view

As a newcomer to angular, I am facing a challenge with the JS file that I have initiated on the index.html page. While working with angular, I have had to create partial views of different pages. The functions in this file handle tasks such as minimizing a ...

Error: Attempting to access the 'url' property of an undefined variable, despite specifically checking for its undefined status

Within my React application, I am utilizing the following state: const [functions, setFunctions] = useState([{}]); I have created a test to check if a specific property is undefined: if (typeof functions[functionCount].url !== "undefined") { ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

Prevent parent from scrolling when hovering over a div in HTML5

Unfortunately, the scrolling attribute is not supported in HTML5. I'm facing an issue where I have an svg inside an iframe within a div, and I need to enable scroll functionality within the div while preventing the page from scrolling at the same time ...

Prevent the next ajax request from overwriting the parameter value set in the previous request

When my application makes multiple ajax requests, I encounter a problem where the original set of parameters used for each request get changed by subsequent requests, leading to errors. Let's take an example: Request A initially sets an index of 0 in ...

The Javascript style.opacity function eliminates the leading zero from the input string

In my application, users have the ability to change the color of the background but not the pattern. They can adjust the background behind the pattern and the opacity of the pattern. Users are prompted to input a percentage, which is actually a number betw ...

Tips for adjusting the dimensions of a cube using keyboard shortcuts:

Adjusting the cube size involves keeping one face stationary while others move and change in position or dimension. The height, depth, and width must be expanded or contracted based on user input from the keyboard. I have managed to create a cube, but so ...

Altering the dimensions of a <div> based on the retrieved data

I am currently retrieving data from an API and displaying certain properties using mapping. I would like to adjust the width of the component based on the value of these properties. <h5> <span className="viewcount" ref={boxSize}> ...

Extract information from a lengthy text (vcard)

While scanning data from a vcard QR-code, the string I receive always follows this format: BEGIN:VCARD VERSION:2.1 N:Lastname;Firstname FN:Firstname Lastname ORG:Lol Group TITLE:Project Engineer TEL;WORK:+32 (0)11 12 13 14 ADR;WORK:Industrielaan 1;2250 Ol ...

Issue with Angular UI Router arises when state cannot be resolved upon page reload

I'm currently facing an issue with routing that I mentioned in the title. Even though my route is functioning, it encounters difficulties when the page is reloaded. Below is the routes object: { state: 'locations', config: { ...

Res.end isn't halting the script's execution process

I'm currently facing an issue while building an API around a third-party API in my Express route. The problem is that the script keeps executing even after encountering a 406 error. Below is the snippet of my code: app.get('/submit/:imei', a ...