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

Using jQuery to remove the functionality of a file input button is ineffective

I am having trouble with an input type file element: <input type="file" name="val1" /> And I'm using this jQuery code: $("input[name='val1']").off("click"); However, the above script, which is already included in a $(function() { } ...

Using jQuery's .load function to load an HTML file from a href attribute into a div element may not function as

I'm struggling to populate the href section of my dropdown menu with my files. I'm attempting to dynamically load the files in the .where-you-tune class. Something must be off because I keep encountering (index):81 Uncaught TypeError: $(...). ...

What could be the reason for this code returning a "module not found" error?

Within localbase.js... const fs = require("fs"); if(!fs.existsSync(__dirname + "/localbase.json")) fs.writeFileSync("./localbase.json", "{}"); let database = require("./localbase.json"); The code abov ...

Struggling with implementing ng-repeat in AngularJS for displaying HTML content

I stumbled upon a post that covers pretty much what I'm trying to achieve: AngularJS - Is it possible to use ng-repeat to render HTML values? Currently, the code appears like this and displays correctly as text: <div ng-repeat="item in items.Item ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

Tips on how to prevent certain classes from being impacted by a hue-rotate filter applied to all elements on a webpage

I am currently in the process of adding a feature that allows users to choose between a dark or light theme, as well as select a specific theme color for the app. The implementation involves using CSS filters such as invert(1) for the dark theme and hue-ro ...

Tips on concealing a div until the value of a specific field surpasses zero

In order to ensure that users focus on the first section of the form before proceeding, I plan to hide the last section until a specific field has a value greater than zero. Check out my HTML code below: <div class="fieldcontainer"> <label>E- ...

Is it more efficient to declare a variable or directly return the variable from the Element's getText() promise in Protractor?

I am facing a scenario where I need to retrieve the text of a web element using a promise and then extract a specific part of the string for further processing. Which example, the one at the top or the bottom, should I use? var id = element(by.binding( ...

Elements are not detected after applying display:none

Within the onLoad event, I implemented a function to hide multiple div elements by setting their CSS property display to "none" and assigning them the class name "invisible": function hideContent() { laElements = document.getElementById("content").chil ...

JavaScript code to make titles slide in as the user scrolls

Looking for a better way to make all titles slide in upon scrolling instead of coding individually? Consider using a forEach loop! Here's how you can modify the code below: function slideInLeft() { document.querySelectorAll('.subtitle-left ...

Disable reloading when submitting and reset input fields after submission

I am working on developing a website where users can post things and comments without the need to refresh the page. I have encountered some issues while implementing this feature and need some assistance with it. My goal is to allow users to submit comment ...

Change the default values for grid column configurations in Ext JS globally

The Ext.grid.column.Column class contains the following configurations: draggable (Default: true) sortable (Default: true) menuDisabled (Default: false) Is there a way to globally change the default values of these configurations for all grid columns i ...

JavaScript inquiry

How do you typically utilize JavaScript in your projects? I often use it for form validation, creating dropdown menus, and more. Do you have any unique ways of using JavaScript? Personally, I find jQuery to be a superior tool in certain situations... ...

Ways to store AJAX response data for future use

I am struggling with implementing the getState function. My goal is to update a field on click using a state value retrieved from an AJAX call. I have come across mentions of promises in other responses, but I am unsure how to integrate them into my code ...

Utilizing jQuery with variable assignment: A beginner's guide

Struggling to utilize a variable in jQuery? In the script snippet below, I set a variable "divname" with a value, but when using jQuery for fading out, it doesn't work as expected. What I really want is for the description to fade in when hovering ove ...

Using AJAX to retrieve additional JavaScript code or functions from the server

It's common knowledge that AJAX is often utilized to request a web part in HTML format from the server. However, is it feasible to use AJAX to request a script that includes functions? ...

Learn how to effortlessly update models by integrating AngularJS with Django and Django Rest Framework

Here is a JSON representation of a post based on its ID: http://127.0.0.1:8000/update/1?format=json {"title": "about me", "content": "I like program", "created": "2014-11-29T18:07:18.173Z", "rating": 1, "id": 1} I am attempting to update the rating ...

jQuery form validation with delay in error prompts

I am experiencing a strange issue with my HTML form validation function. It seems to be showing the alert div twice, and I can't figure out why this is happening. Adjusting the delay time seems to affect which field triggers the problem. Can anyone sp ...

Exploring the concept of reflection in JavaScript and jQuery

Here is a javascript object I have: person.Name = "John"; person.Nick = "Smith"; person.Info = "hi there"; In addition, I have some HTML elements as shown below: <input id="Name" /> <input id="Nick" /> <input id="Info" /> My question ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...