I am encountering TypeError issues while attempting to mock/test Vuex store modules

I'm currently in the process of learning how to effectively test components and JavaScript code, but I have hit a roadblock with Vuex modules. Below is the code snippet for the test:

import { shallowMount } from '@vue/test-utils'
import WorkoutsHistory from '../../src/components/WorkoutsHistory.vue'
import workout from '../../src/store/modules/workout'

const mocks = {
  $store: {
    modules: {
      workout
    }
  }
}
const propsData = {
  show: false
}

let wrapper

describe('WorkoutsHistory.vue', () => {

  beforeEach(() => {
    wrapper = shallowMount(WorkoutsHistory, { mocks, propsData })
  })

  it('should match snapshots', () => {
    expect(wrapper).toMatchSnapshot()
  })

  it('should render the workout-list', () => {
    expect(wrapper.find('.workout-list')).toBeTruthy()
  })

})

The imported module looks like this:

import mutations from './mutations'

const state = {
  exercises: {},
  workouts: {}
}

export default {
  namespaced: true,
  state,
  mutations
}

The issue I am facing is quite straightforward - when I run the test, it returns an error:

TypeError: Cannot read property 'workout/' of undefined
. This seems strange to me as I have defined the structure exactly as it is in the Vuex Store (I also tried using \createLocalVue). Here is the script for the component:

<script>
import { mapState } from 'vuex'
import NewExercise from './NewExercise'

export default {
  name: 'WorkoutsHistory',
  components: { NewExercise },
  data() {
    return { show: false }
  },
  computed: {
    ...mapState('workout', ['workouts'])
  },
  methods: {
    showForm() { this.show = !this.show }
  }
}
</script>

Do you have any suggestions or insights on how to troubleshoot this issue?

Answer №1

The reason for this issue is that you are mocking the $store property on your component, but not utilizing it in the correct way within your component. Instead, your component is using the ...mapState() method, which expects a Vuex.Store() to be instantiated locally on Vue. To address this, check out the link below for guidance on properly setting up a Store for unit/integration tests for a local component:

https://vue-test-utils.vuejs.org/guides/using-with-vuex.html

A big thanks to @Anatoly for sharing this helpful resource.

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

Eliminate the standard blue border that appears when control-clicking on table elements

I've encountered this question before, but unfortunately none of the solutions provided have worked for me. Some things I've attempted are: Using event.preventDefault() - did not produce the desired result. Removing user-select from CS ...

How can I retrieve the current session's username when passport.js is returning a promise containing `{false}` for `req.user`?

While working in Node.js, I implemented the passportJS LocalStrategy to handle user authentication. One of the functionalities I used was req.getAuthenticated() This function allows me to check if the current session is authenticated. Next, I needed to r ...

Achieving dynamic height in a parent div with a sticky header using mui-datatables

Here are the settings I've configured for my mui-datatables: const options = { responsive: "standard", pagination: false, tableBodyHeight: '80vh', }; return ( <MUIDataTable title={"ACME Employee ...

Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA. These errors keep popping up: index.js // main Firebase file import { initializeApp } from 'firebase/app' import { getAuth } from 'firebase/auth' ...

The v-for loop specifically iterates over an array that relates to the current dynamic page number

I keep track of results per page number, illustrated below: <ul v-for="item in listingsData" :key="item.id"> <li>{{ item.name }}</li> </ul> <button @click="pushPrev">Push Prev Results</butt ...

JQuery is failing to properly return the string containing special characters like apostrophes

Storing the name "Uncle Bob's Organic" in the data-Iname attribute caused a retrieval issue, as it only retrieved up to "Uncle Bob". Here is the process used for retrieving the value from the data-Iname: var itemName = $(this).attr("data-Iname"); T ...

The process of uploading images with VueJS and Laravel via API is experiencing difficulties

I am currently facing an issue with uploading images using Vue.js and Laravel via API. When I send the image information from Vue.js to Laravel through the API, it seems that Laravel is not receiving the data in the correct format, resulting in an error be ...

Indeed, conditional validation is essential

I have encountered an issue with my schema validation where I am trying to validate one field based on another. For example, if the carType is "SUV", then the maximum number of passengers should be 6; otherwise, it should be 4. However, despite setting u ...

Unable to access remote video streams by directly modifying URL parameters

Recently, I delved into experimenting with the straightforward mediasoup demo available at: https://github.com/Dirvann/mediasoup-sfu-webrtc-video-rooms After setting up the demo, everything seemed to be functioning correctly. The initial task on my agend ...

The CSS styles are functioning correctly in index.html, but they are not applying properly in the component.html

When the UI Element is clicked, it should add the class "open" to the list item (li), causing it to open in a collapsed state. However, this functionality does not seem to be working in the xxx.component.html file. Screenshot [] ...

What is the best way to combine multiple periods into a single range?

I am on a quest to find a way to transform sound frequency into light frequency, essentially turning sound into color. Currently, I have managed to come up with a straightforward formula that converts the sound frequency into the light frequency range: co ...

Is it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I proper ...

Utilizing recursive AJAX requests and halting execution at a specified condition

After hours of searching and attempting, I am struggling as a beginner with ajax concepts. Here is my issue: 1. I have a page that retrieves the current date's data from the database, so I am using an ajax function recursively with a setTimeout of 10 ...

Is there a smooth and effective method to implement a timeout restriction while loading a sluggish external file using JavaScript?

Incorporating content from an external PHP file on a different server using JavaScript can sometimes be problematic. There are instances where the other service may be slow to load or not load at all. Is there a method in JavaScript to attempt fetching th ...

Tips for manually adding CSS/JS files for offline usage with Vue.js CLI

I am currently utilizing Vue.js CLI alongside AP.NET Core in a single-page application. I have identified the need to bundle some JavaScript/CSS files locally instead of relying on a CDN due to potential deployment scenarios without internet access. The co ...

Struggling to fetch the latest state value in React with hooks?

I have implemented functional components with 2 radio buttons and a submit button. However, upon clicking the submit button, I am unable to retrieve the updated value properly. Check out my code at this link. To reproduce the issue: Start the applicatio ...

Continuous Scrolling with Callback Function in jQuery

I have implemented the infinite-scroll plugin, which replaces traditional pagination with ajax to fetch new pages. The issue I am facing is that jQuery functions do not recognize the new posts, causing certain functions like the ones below to stop working ...

Issue with setting HTML content using jQuery's .html() method

I have a simple functionality. When a user clicks on the edit link, it transforms the previous element into an input element for editing, and changes the edit link into a cancel link. If the user decides not to edit, they can click on cancel and everything ...

How can the refresh event be detected within an iframe by the parent document?

Consider this scenario: We are dealing with a file upload page where we aim to avoid reloading the entire page upon completion of the upload process. To achieve this, we have enclosed the form within an iframe. The form within the iframe posts to itself an ...

Automated tools and frameworks for the testing of website performance

Hello, I have a website that heavily relies on AJAX for server communication. I am looking to conduct performance and stress testing using automated scripts. Can you provide any suggestions or recommendations? I am specifically interested in the functiona ...