Error: The 'getters' property is undefined in @vue/test-utils and cannot be read

I've been utilizing @vue-test-utils for unit testing in VueJS.

This is what my store setup looks like:

export default {
 root: true,
 state: {
    batches: []
 },
 getters: {
 getBatches: state => {
    return state.batches
  }
 }
}

The component has the following structure:

<template>
  <div>
   <p>Batches Work!</p>
  </div>
</template>

<script>
  import { mapGetters } from "vuex";

  export default {
    computed: {
      ...mapGetters({
         getBatches: "getBatches"
      })
   }
  }; 
 </script>

The test file is structured as follows:

 import { shallowMount, createLocalVue } from '@vue/test-utils'
 import Vuex from 'vuex'
 import Vuetify from 'vuetify'
 import Vue from 'vue'
 import Batches from '../../../src/pages/Batches'

 const $route = {
    path: '/batches'
 }

 const localVue = createLocalVue()
 localVue.use(Vuex)
 Vue.use(Vuetify)

  describe('Batches', () => {
   let getters, store

   beforeEach(() => {
    getters = {
     getBatches: () => jest.fn()
    },
    store = new Vuex.Store({
        getters
    })
 })

 const wrapper = shallowMount(Batches, {
 localVue,
 mocks: {
    $route
   },
   store
 })

 it('Batches is a vue component', () => {
    expect(wrapper.isVueInstance()).toBeTruthy()
 })

})

Upon running the test, I encounter the following error message:

 FAIL  test/unit/pages/batches-test.spec.js
 Batches
   ✕ encountered a declaration exception (2ms)

 ● Batches › encountered a declaration exception

 TypeError: Cannot read property 'getters' of undefined

 at VueComponent.mappedGetter (node_modules/vuex/dist/vuex.common.js:898:73)
 at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4459:25)
<Additional error details here>
...
 console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
 [Vue warn]: Error in render: "TypeError: Cannot read property 'getters' of undefined"

I have tried different methods to make my test work with vuex resources but seem to be stuck. I can't figure out where I am going wrong. Any assistance would be greatly appreciated!

Answer №1

Make sure to implement the same getter in your test file as you have in your main file when creating tests.

Answer №2

If you're attempting to utilize both localVue and Vue simultaneously, it will not function properly. Furthermore, components reliant on Vuetify should not be used with localVue

With that in mind, the specification could be restructured as follows:

import { shallowMount } from '@vue/test-utils';
import Vuex from 'vuex';
import Vuetify from 'vuetify';
import Vue from 'vue';
import Batches from '../../../src/pages/Batches';

Vue.use(Vuex);
Vue.use(Vuetify);

describe('Batches', () => {
  it('Batches is a vue component', () => {
    const store = new Vuex.Store({
      modules: {
        module: {
          getters: { getBatches: () => jest.fn() },
        },
      },
    });

    const $route = {
      path: '/batches',
    };

    const wrapper = shallowMount(Batches, {
      Vue,
      mocks: {
        $route,
      },
      store,
    });

    expect(wrapper.isVueInstance()).toBeTruthy();
  });
});

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

What steps can I take to detect errors when generating a MongoDB ObjectId in Node.js?

var selectedCriteria = Mongoose.Types.ObjectId(payloadData.skillId), If an incorrect Id is passed, the following error message will be displayed: Error: Uncaught error: Argument passed in must be a single string of 12 bytes or a string of 24 hex charac ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

Including onMouseUp and onMouseDown events within a JavaScript function

I am experiencing an issue with a div that contains an input image with the ID of "Area-Light". I am attempting to pass the ID of the input image to a function. Although event handlers can be directly added inside the input tag, I prefer to do it within ...

The proper way to specify the data model in vuejs

If we are designing an abstract data model for a Vue application, should we create a file named Person.vue or Person.js? <script> export default { props: { firstName: String, lastName: String } } </script> class Person { constr ...

Controlling LED lights using Johnny-Five and Arduino in NW.js

I have a setup with my board that includes two buttons (each with pull-up resistors) and two LEDs. My goal is to make each button activate its corresponding LED while deactivating the other one. Here's the code I'm using: var five = require(&ap ...

Remove files from the server using an AJAX request

I am attempting to delete files on the SERVER using JavaScript, and I have already consulted the advice provided in this JavaScript file deletion thread My current JavaScript code looks like this: deleteFile = function() { return $.ajax({ url: "de ...

Extend jQuery deeply, only replacing values and not adding new keys

For instance, consider the following two JSON objects: First Object: { "surname" : "Raghuvanshi", "work" : { "title": "title1" }, "name" : "Navin" } Second Object: { "work" : { "title": "title2", "field": "field2" }, "name" ...

Instructions on how to insert the meta tag with the attribute "http-equiv" set to "REFRESH" and the content "0; URL="somedomain"" into a division on a

Trying to send an ajax request to a page that includes the following meta tag: <meta http-equiv="REFRESH" content="0; URL=https://www.ohterDomain.com/help?nodeId=2&view=content-only"> After making a successful ajax call, the correct content is ...

Encountering difficulties in importing TailwindCSS

Having trouble importing TailwindCSS and applying CSS? Here's how it's included in my package.json: "devDependencies": { "autoprefixer": "^10.2.4", "css-loader": "^5.1.1", "postc ...

Steps to completely eliminate all elements from an object using specific keys

I have been pondering the most efficient method to delete all elements of an object through an onClick function. The goal is for the handler to remove all elements. Despite attempts with methods like the delete keyword and filtering, clicking the clear all ...

retrieve room from a socket on socket.io

Is there a way to retrieve the rooms associated with a socket in socket.io version 1.4? I attempted to use this.socket.adapter.rooms, but encountered an error in the chrome console: Cannot read property 'rooms' of undefined Here is the method I ...

Exploring the Power of Map with Angular 6 HttpClient

My goal is to enhance my learning by fetching data from a mock JSON API and adding "hey" to all titles before returning an Observable. Currently, I am able to display the data without any issues if I don't use the Map operator. However, when I do use ...

What could be preventing this AJAX call from running correctly?

I am in the process of developing a website that provides users with a discount based on a promotional code they can input. It is important for me to verify the validity of the code in our database before allowing a new sign-up to proceed. Below is the AJA ...

Why isn't my Enum functioning properly to display the colored background?

Why isn't the Background Color showing up when I pass in the BGColor Prop dynamically in my next.js + Tailwind app? I have tried passing in the prop for my component, but the color is not appearing. <Title title='This is HOME' descripti ...

What is the best way to execute Jest tests concurrently using the VSCode extension?

Running the Jest tests in band is essential to prevent errors from occurring. However, I am unsure of how to resolve this issue. The tests run smoothly when executed through the command line. ...

Experiencing difficulties with knockout bindings

I have a situation where I have multiple tabs labeled A, B, and C, and upon loading the 'C' tab, the model properties should data-bind to tab 'C'. I am encountering an issue with data binding. These three tabs (A, B, C) are located ins ...

[VUE ALERT]: Issue found in mounted hook: "The variable this.$refs.canvas is not defined."

I have integrated Vue Chart into one of my projects, but I am encountering an error. Here is the code for the Chart Component: <line-example></line-example> And below is my script: <script> import Navbar from '@/components/navb ...

Utilizing Vuex for managing diverse array types

Creating a filter: Changes export default { state: { filteredItems: [] }, mutations: { updateFilterList(state, data) { if (state.filteredItems.includes(data)) { state.filteredItems = state.filteredItems.filter(item => item !== data); } e ...

Creating a Dynamic Bar in Your Shiny Application: A Step-by-Step Guide

Currently, I am developing a unique crowd funding shiny app to monitor donation amounts. Is there a method available that allows for the creation of a reactive bar in Shiny? Alternatively, is it feasible to achieve this using html, css, and javascript? He ...

App.controller attributes in HTML tags are not receiving the value of the HTML variable

In the process of developing a simple student-teacher web application, I am utilizing AngularJS to handle the front-end. Within my JavaScript file, there are two app controllers - one for fetching student data and another for retrieving subjects assigned t ...