When attempting to import a store in the routes.js file while running Jest tests in Vue.js, an error

My current setup involves using vue-test-utils along with jest for Test-Driven Development (TDD). In the route file (routes.js) of my Vue.js application, I have imported the $store object and utilized it for various functionalities. While writing a basic unit test for the login page, I encountered an error even before any tests could be executed.

Error:

   TypeError: Cannot read property 'state' of undefined

      130 |             isAuth: true,
    > 131 |             layout: $store.state.dom.isMobile ? mobileSinglePage : panel
          |                            ^
 

route.js:

import $store from "../store"

// --------- layouts
import panel from "../layout/panel";
import mobileSinglePage from "../layout/mobileSinglePage";
import MainLayout from "../layout/index";
import auth from "../layout/auth"


// transactions
import _transaction from "../pages/transaction/_transaction"

const routes = [
    {
        path: "",
        component: MainLayout,
        children: [
            {
                path: "",
                redirect: "/panel/dashboard",
            },
            {
                path: "login",
                component: login,
                name: "login",
                meta: { 
                     preventLoggedIn: true,
                     layout: auth
                }
            },
            {
                path: "/panel/transactions/:url",
                name: "_transactions",
                component: _transaction,
                meta: { 
                    isAuth: true,
                    layout: $store.state.dom.isMobile ? mobileSinglePage : panel
                }
            },
            {
                path: "*",
                name: 'error_page',
                redirect: '/404'
            }
        ],
    },
];
export default routes;

login.spec.js



import { mount, createLocalVue } from "@vue/test-utils"
import login from '@/pages/auth/login'
import Vuex from "vuex"

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


describe("login", () => {
    it("simple test", () => {
        const wrapper = mount(login, {
            localVue,
            data(){
                return {
                    form: {
                        mobile_number: '',
                    },
                }
            },
        })
        wrapper.find('#login').text()

    })
})

Login.vue

<template>
  <div class="w-100">
    <transition>
      <form @submit.prevent="requestOtp" class="w-100" v-if="step === 1">
        <MobileInput
            ref="mobile_number"
            v-model="form.mobile_number"
            autocomplete="false"
            outlined
            :counter="false"
            label="mobile number"
        />
        <AppButton
            :disabled="!form.mobile_number || form.mobile_number.length !== 11"
            type="submit"
            color="secondary"
            large
            :loading="loading"
            class="w-100 fontMobileMedium font0.875 loginBtn">
          login
        </AppButton>
      </form>
    </transition>
    <transition>
      <form @submit.prevent="verifyOtp" v-if="step === 2">
        <AppPinCode
            autofocus
            dir="ltr"
            :disabled="loading"
            :length="6"
            class="mb-6"
            @complete="verifyOtp"
            v-model="form.otpCode"/>
        <AppButton
            type="submit"
            :loading="loading"
            :disabled="!form.otpCode"
            color="secondary"
            large
            class="w-100 fontMobileMedium font0.875 ">
          login
        </AppButton>
      </form>
    </transition>
  </div>
</template>
<script>
    // Import statements and code for Login.vue...
</script>

store/dom.js(store module)

// Code for store dom.js...

store/index.js

// Code for store index.js...

It seems that the error related to the router object is being thrown in the test file without explicitly using it. This issue needs further investigation.

Answer №1

It seems like your Login.vue file is utilizing both router (

this.$router.push({name: 'dashboard'})
) and store (...mapActions('main', ['crud']),), but neither are given during mount.

You may want to provide both of them:

import { mount, createLocalVue } from "@vue/test-utils"
import login from '@/pages/auth/login'
import Vuex from "vuex"
import VueRouter from "vue-router"

const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(VueRouter)


const store = new Vuex.Store({
  state: {
    // Define your minimal default state here
  },
  actions: {
    // At least include the 'main.crud' action here
  }
})

const routes = [
  // Include minimal routes here
]

const router = new VueRouter({ routes })

describe("login", () => {
    it("simple test", () => {
        const wrapper = mount(login, {
            router,
            store,
            localVue,
            data(){
                return {
                    form: {
                        mobile_number: '',
                    },
                }
            },
        })
        wrapper.find('#login').text()

    })
})

For more information, check out here and here.

Additionally, make sure to place mapActions() in the methods section rather than data (Refer to here).

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

Whenever a user tries to retrieve a page using ajax and then proceeds to submit the form associated with that page, they encounter

In my addQuestions.php file, I have four options available - single, multiple, matrix, and true false type questions with values 1-4 assigned to each respectively. To dynamically load the appropriate question type based on user selection, I am using AJAX w ...

What is the procedure for placing an item into a vacant area in react-dnd?

Looking to create a drag and drop list using react-dnd. Manage to put together an example: visit codesandbox example here Currently facing one issue: Unable to drop an item into an empty section. If trying to move image1 to the first or third group, un ...

The dropdown menu is dynamically populated based on the selection from another dropdown menu, with options retrieved from

Apologies if this has been addressed previously, but the existing solutions do not seem to work for me. I have 5 dropdowns: Brand, Model, Color, Engine No., and Chassis No. My query pertains to how I can link the dropdown options for Model based on the sel ...

Can we accurately pinpoint individual LineSegments in three.js by hovering over them, especially those with unique geometries?

Creating two examples of drawing lines in three.js was quite a fun challenge. One example showcased different geometry and material, while the other kept it simple with just one geometry and material. The demonstration links can be found here: Example 1 an ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

Creating a PDF document using html2pdf: A step-by-step guide

Currently, I am immersed in a project using React. The main goal right now is to dynamically generate a PDF file (invoice) and then securely upload it to Google Drive. In the snippet of code provided below, you can see how I attempted to create the PDF f ...

Tips for serializing the execution of an array of observables

I am currently working on a validation process that goes through data in a table row by row. Due to the fact that each row validation requires access to a shared resource, it is crucial that the access to this resource is serialized. public validate():Obse ...

Encountering a JavaScript/TypeScript issue that reads "Unable to access property 'Items' as it is undefined"

I encountered an issue with Javascript where I'm receiving an error message stating "Cannot read property 'Items' of undefined". The this keyword is consistently showing as undefined in the Base class. How can this problem be resolved? Coul ...

Retrieve a single document from Firestore and assign it to a variable

While I'm still new to NodeJS, I'm currently working on retrieving a single User document from Firestore. const fs = firebase.firestore(); const usersRef = fs.collection('users'); let findUserByContact = (contact) => { let res ...

The best practices for integrating Firebase with REST APIs

While searching for a tutorial on integrating REST APIs with Firebase, I came across numerous code snippets utilizing the curl method calls or other helper libraries. However, what I couldn't find were the basics - such as where to call these methods ...

The attempted use of Wget with JavaScript integration was unsuccessful

Is there a way to save a dynamically generated page from the command line? I attempted to download it using: wget PageWithJS.com -O output.html However, the output.html file does not include the dynamically generated content. Any suggestions? ...

Resolving CORS problem: Eliminating the 'Access-Control-Allow-Origin' Response Header in Angular

Recently, the backend API located at has been proxied by an F5 device which automatically includes the CORS header Access-Control-Allow-Origin: * in all responses. However, the GUI code seems to also be adding a CORS header with Access-Control-Allow-Origi ...

Guide: Installing Vuetify 2.5.6 on Vue 3

take a look at the code snippet from my main.js file: import { createApp } from 'vue' import vuetify from './plugins/vuetify' import App from './App.vue' const app = createApp(App) app.use(vuetify) app.mount('#app' ...

Can I obtain a link through the branch_match_id parameter?

Within my application, there exists a hyperlink: hxxp://get.livesoccer.io/IuKk/0CRq5vArLx which leads to the following destination: hxxp://livesoccer.io/news.html?url=http%3A%2F%2Fwww.90min.com%2Fembed%2Fposts%2F4003374-chelsea-star-pedro-loving-life-at-s ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

Is there a way for me to insert a variable into the src attribute of my img tag like this: `<img alt="Avatar" src=`https://graph.facebook.com/${snAvatarSnuid}/picture`>`

I need assistance with passing a variable called snAvatarSnuid within the img src tag, specifically after facebook.com/ and before /picture as shown below: <img alt="Avatar" src=`https://graph.facebook.com/${snAvatarSnuid}/picture`> Note: 1) The ht ...

Passing and Retrieving Specific Item from Mapped Array in React/Mobx: A guide on sending a single item from a mapped array to another component and accessing only

My API data is stored in a store called PositionStore, which includes information such as loading status, error messages, and an array of items. Here's how it looks: const PositionStore = observable({ loading: false, error: "", items: [] as ...

Searching for the most recent selected element from a multiple select tag in jQuery

Incorporating a <select multiple="multiple" id="multi"> on my website, I've implemented a jQuery script with the following function: $("#multi").on("change", function(){}) My goal is to retrieve the most recently selected item from the select ...

My applications are not firing the deviceready event as expected

Struggling to incorporate a cordova plugin into my vue.js project using vue-cordova. Specifically, I am attempting to utilize the open-native-settings plugin to access device settings on iOS or Android. While it works seamlessly in the demo app provided b ...

Display the DIV specifically for visitors arriving from Facebook

I want to display a specific DIV on the product page only if the user has visited from Facebook. Currently, I am using the following code to check if they arrived from Facebook: var ref = document.referrer; if (ref.match(/^https?:\/\/([^\ ...