A guide on harnessing the power of Jest when integrating it with vuex-module-decor

In my Typescript-written Vue component, I am facing an issue while trying to write a unit test using vue-test-utils and jest. The problem arises when injecting the vuex store that was created with vuex-module-decorators.

Below is a snippet from my Vue component:

mycomponent.vue

<template>
  <v-autocomplete
     v-model="job
     :items="jobs"
     outlined
     dense
     @change="editJob"
  />
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { jobsWantedStore } from '../../utils/store-accessor'

@Component
export default class SelectJob extends Vue {

    async editJob() {
            try {
                await jobsWantedStore.EDIT_JOB(this.job)
            } catch (error) {
                this.error = error
            }
        }
    }

}
</script>

The related vuex store code is as follows:

/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { Module, VuexModule, Action, Mutation, getModule } from 'vuex-module-decorators'
import { PrioritisedJob } from '~/models'
import JobsWantedService from '~/services/jobs-wanted-service'

// Rest of the code here...

And here is the store accessor:

/* eslint-disable import/no-mutable-exports */
import { Store } from 'vuex'
import { getModule } from 'vuex-module-decorators'
import jobsWanted from '../store/jobsWanted'

// Rest of the code here...

My test file looks like this:

job.spec.js

import { shallowMount, createLocalVue } from '@vue/test-utils'
import mycomponent from '@/components/mycomponent.vue'
import Vuetify from 'vuetify'
import Vuex from 'vuex'

// Rest of the test code here...

When running the tests, it shows that jobsWantedStore is undefined, causing issues with the test execution. Any suggestions on how to properly inject the store using vuex-module-decorators?

Answer №1

I encountered a similar issue as well. Just to clarify: the component, store module, and store accessor mentioned in the question are reminiscent of what I previously worked with. It seems like we both may have referenced examples from vuex-module-decorators on GitHub.

I prefer not to share the entire testing spec code since it aligns closely with what Elsa had provided. However, here's the key missing part that made a difference for me. What ultimately resolved the issue for me was invoking initialiseStores within the beforeEach hook, as demonstrated below:

import { initialiseStores } from '~/store';

describe('MyComponent test', () => {
  ...
  beforeEach(() => {
    initialiseStores(store) // provide your mock store instance
  })
  ...
}

Answer №2

Oops, I realized that I neglected to include localVue while setting up my wrapper! The correct way to do it is:

wrapper = shallowMount(SelectJob, {
    propsData,
    localVue,
    vuetify,
    store,
})

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

Vue Awesome Lightbox - Error: Unable to access property 'match' of an undefined object

I'm facing an issue with my image gallery which uses the component "vue-cool-lightbox". Previously, when clicking on a picture, the lightbox would appear as expected. However, after dynamically loading my "projects" using axios, the lightbox no longer ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

Navigating through alterations in intricate data utilizing the BehaviorSubject concept

If I have a Service that offers a BehaviorSubject to any component needing the most up-to-date version of certain data, how can these components differentiate what changed in the data when they receive notifications? export class DataService { pri ...

Unable to retrieve the API key in Nuxt framework

I am fairly new to NuxtJS and have been following tutorials on it. I am having trouble displaying the {{planet.title}} on my page. However, when I use {{$data}}, I can see all the planets. I want the title of the planet's name that I have in the slug ...

Implementing an extended interface as an argument in a function

Here is the code snippet for analysis: interface IUserData { FirstName: string, LastName: string, Email: string, Password: string } interface IState extends IUserData { isSuccess: boolean } const state: IState = { FirstName: &apo ...

Setting a variable based on the stage of its deployment in a DevOps environment: What you need to know

Is there a way I can easily update a variable in a React app based on the stage of an Azure DevOps release pipeline? For instance, if I have dev, QA, and production stages set up, and I want to change the client ID in the auth configuration for each envi ...

Dynamically load current components in Angular 2's final release

In my quest to dynamically load a component in the upcoming release version 2.0.0, I encountered some challenges. Previously, in RC5, I utilized the following code for loading: I created a directive responsible for loading the controls: import { Check ...

typescript library experiencing issues with invalid regex flags in javascript nodes

I am facing an issue while attempting to import a plain JavaScript module into a Node application written in TypeScript. The error below is being thrown by one of the codes in the JavaScript module. b = s.matchAll(/<FILE_INCLUDE [^>]+>/gid); Synta ...

When instance data is altered during an ajax submission, the input data is reset

Within my Vue instance, I have implemented the following method: ajaxSubmit: function(event) { this.loader = true; var form = event.target; var action = form.getAttribute('action'); var data = new FormData(f ...

At random intervals, a ReferenceError is triggered stating that Vue is not defined

While working on an application that uses templates rendered by Apache Velocity, I encountered the error "Uncaught ReferenceError: Vue is not defined" when trying to incorporate vue.js components. Oddly enough, this error is not consistent - it occurs most ...

What is the process for parameterizing a tuple in coding?

In my scenario, I have a tuple with interrelated types. Specifically, it involves an extractor function that retrieves a value, which is then used as input for another function. What I envision conceptually looks like this code snippet, although it does n ...

Is it feasible to invoke a method without any arguments on this basic subscription?

A BRIEF SUMMARY Implementing an observable in my code, I strive for maintaining cleanliness and efficiency by utilizing the detectChanges() method to update *ngIf= in the HTML. QUERY Is there a way to invoke the detectChanges() method within subscribe() ...

Strange "hash" symbol at the end of URL on the local server

Currently experimenting with a Laravel and Vue project locally, I have vue-router configured but my URLs appear as follows: <virtual-host>.loc/#/. Upon accessing my virtual host, the page loads but I notice this strange #/ added to the end of the UR ...

Angular sets the required property only when the button is clicked

Is there a way to make a field required in Angular only when a button is clicked? Currently, the error message appears even before the user interacts with the field. I would like the error message "folder name is required" to only appear when the user cli ...

React validation functionalities

Incorporating React, I am attempting to implement a validation feature within a footer containing multiple buttons with unique values such as home, orders, payments and more. My goal is to dynamically display an active state for the button corresponding to ...

Utilizing Vue.js keep-alive to optimize performance by excluding Ionic components

The components from a specific library are not compatible with Vue.js' keep-alive feature. I have attempted to exclude them using exclude="/^ion-*./", but it has not been successful. These components do not have a designated name. Is there a way to p ...

Learn how to transform an object into an array consisting of multiple objects in TypeScript

The car's details are stored as: var car = {model: 'Rav4', Brand: 'Tayota'} I need to convert this information to an array format like [{model: 'Rav4', Brand: 'Tayota'}] ...

Error: Certain Prisma model mappings are not being generated

In my schema.prisma file, I have noticed that some models are not generating their @@map for use in the client. model ContentFilter { id Int @id @default(autoincrement()) blurriness Float? @default(0.3) adult ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

Exploring the use of MediaSource for seamless audio playback

Currently working on integrating an audio player into my Angular web application by following a tutorial from Google Developers and seeking guidance from a thread on Can't seek video when playing from MediaSource. The unique aspect of my implementati ...