Encountered issue in mounted hook: "TypeError: Unable to access 'dispatch' property of undefined"

I need help writing a test for my Vue component. The component makes an async call on mount and updates the Vuex store, but this causes issues with my current unit tests because 'dispatch' is called during mount. Does anyone have any suggestions on how to solve this problem? I am mocking table data so the mounted() function doesn't need to be triggered when running the tests.

MyTable.spec.js

     const wrapper = shallowMount(MyTable, {
        propsData: {
            tableData: [
                {
                    "product_id":10826345236,
                    "name":"T-Shirt"
                }
            ],
            columns: ['product_id', 'name'],
            headings: ['Product ID', 'Name'],
            actionType: 'loadProducts'
        }
    });
    ...

MyTable.vue

    ...
    data() {
        return {
            options: {
                ...
            }
        };
    },
    methods: {
        getHeadings() {
            let headings = {};
            this.columns.map((key, i) => headings[key] = this.headings[i]);
            return headings;
        },
        setColumnClasses() {
            let classes = {};
            this.columns.map((key) => classes[key] = key);
            return classes;
        },
        loadRecords(actionType) {
            this.$store.dispatch(actionType);
        }
    },
    props: {
        tableData: {
            type: Array,
            required: true
        },
        columns: {
            type: Array,
            required: true
        },
        actionType: {
            type: String,
            required: true
        },
        headings: {
            type: Array,
            required: true
        },
        ...
    },
    mounted() {
        this.loadRecords(this.actionType);
    }

Answer №1

You're receiving this error message because Vue expects this.$store to be defined when mounted, but it's not imported or mocked in your application.

Here is the test function code you provided:

const wrapper = shallowMount(MyTable, {
  propsData: {
    tableData: [
      {
        "product_id":10826345236,
        "name":"T-Shirt"
      }
    ],
    columns: ['product_id', 'name'],
    headings: ['Product ID', 'Name'],
    actionType: 'loadProducts'
  }
});

Here is what you need to add:

import store from '../path/to/store.js';
import { createLocalVue, shallowMount } from '@vue/test-utils';

// Create a local Vue instance for testing: https://vue-test-utils.vuejs.org/api/#createlocalvue
const localVue = createLocalVue();

// Use Vuex for the store mechanism.
localVue.use(Vuex);

const wrapper = shallowMount(MyTable, {
  localVue, // Bind the local Vue instance for shallow mounting.
  store, // Bind the store to access all methods when invoked.
  propsData: {
    tableData: [
      {
        "product_id":10826345236,
        "name":"T-Shirt"
      }
    ],
    columns: ['product_id', 'name'],
    headings: ['Product ID', 'Name'],
    actionType: 'loadProducts'
  }
});

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 is the best way to transfer the JWT token from the server to the client using an HTTP header?

I have been searching for an answer on how to pass the JWT Token from the client to the server securely, but I am not satisfied with the explanations I found. Everyone talks about the most secure way to transfer the JWT token using HTTP headers instead of ...

Trigger the click event on a specific class selector to extract the corresponding ID

I have an HTML Table with each row: <table> <tr><td><a href='#' id='1' class='delete'>delete</a></td></tr> <tr><td><a href='#' id='2' class='de ...

The specified variable will not be visible in the window object

I recently created a JavaScript code snippet that looks like this: let var1 = 1; window.var2 = 2; After running the code in the Chrome console, I entered window to inspect the global window object. Surprisingly, only the second variable appeared and the ...

The modal in Laravel Jetstream is not displaying

I've been attempting to utilize the Jetstream Dialog Modal for my project, but I'm encountering some issues. Here is a snippet of code that I extracted from the official documentation: <jet-dialog-modal :show="modal" @close="mod ...

Display Nvd3 Pie Chart percentages in decimal format

I have integrated Nvd3 into my Angular project to create various types of charts. Utilizing the angular directive from Krispo's website, I am currently working on a pie chart that displays values in percentages. However, the displayed values are round ...

Unexplained Reference Error in Next.js Typescript: Variable Accessed before Initialization

I am currently working on an admin website and encountered the error Block-scoped variable used before its declaration.. I will provide details using images and code. This is my first time seeking help on StackOverflow. Error Message: Block-scoped variab ...

Incorporate a JavaScript file into a JSON document

Can I import a js file into a json file? I have a js file called config.js module.exports = {id : 'test'} I would like to utilize the id key in my json file, config.json const {id } = require('./config.js') {user_id : id} ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

Deactivate the save button in case of errors occurring with Laravel and Vuetify

Currently, I am utilizing the Vuetify v-text-field within a form. I have implemented some basic validation rules (such as requiring the field to be filled) which can be checked using simple rules like (:rules="[ rules.required ]"). However, in ad ...

Is there a solution to address this login code with multiple queries in Mongoose?

**I am currently in the process of creating a login route that can accept either a username or email. However, I encountered an issue where one field is being set to undefined when the other field is available, resulting in an error. My regex is specific ...

Is it possible to incorporate variables when utilizing NG-CLASS for an active link in Angular?

I am trying to create a navigation using a loop in my code. However, I keep encountering an error which says that it won't evaluate as a string. The idea is to loop through the $scope.navigation and use it to generate the navigation dynamically instea ...

Optimal method of creating and initializing store items in Vue using Vuex

As a newcomer to Vue, I am exploring the best approach to manipulate a "master" store object by stripping keys, renaming others, and creating an altered version to save as a new store item. In my App.js file, I initiate a "loadData" action within the crea ...

Attempting to implement a b-table that can manage multiple arrays within an array

This is the b-table, designed to display a column of food items <b-table :fields="Fields" :items="ITEMS"> <template #cell(food)="data"> {{data.item.food}} </template> </b-table> //Column ...

Various Issues Regarding Jquery Libraries

Here's a question on my mind... Currently, in my main file index.php, I have imported jquery 2.0.3 like this: <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> The issue arises bec ...

Utilizing the button's id to display a partial view within Rails

I am working on a view that showcases a partial containing a list of events created by a user, each with an edit link alongside. My goal is to have a form partial appear below the event when the 'edit' link is clicked. To achieve this, I have su ...

Best practices for implementing the map function with TypeScript

I'm currently working on mapping types in a DB using the Map function in JavaScript. This is my first time trying to do this, and I'm eager to learn but I've hit a roadblock. Here is the structure of the DB: const db = { data: [ { ...

Setting a default value in a multi-select dropdown using react-select

I have taken over management of my first React app, and I am facing a seemingly simple change that needs to be made. The modification involves an email signup page where users can select their interests from a multi-select dropdown menu. My task is to mak ...

Using jquery to submit a form with multiple fields spread across various tabs

Utilizing a bootstrap modal, I aim to display detailed information about a single product. Within this modal, there are three tabs categorized as details, image, and specification for the respective content components of the product. Upon clicking the edi ...

Tips for transitioning from an old link to a new link within an MVC framework

Is there a way to redirect an old link to a new link in MVC? In Google search results, my old URL was cached as www.abcd.com/product?id=64 however, my new URL is now www.abcd.com/product/sample How can I set up a redirect so that when a user clicks on th ...

Creating a structured model design in Javascript using Backbone framework

I am relatively new to JavaScript, so please bear with me as I ask this question. Currently, for my project, I am using NodeJS for the server and Backbone for the client. The idea is that the client will send a request to the server, which will then respo ...