What are the proper methods for accurately testing vuex state and mutations?

Can someone guide me on how to properly test mutations and state? I have a modal window component that is rendered when the showModal property in the state is true. There is an event triggering a mutation that changes this property. How can I verify that after the event is triggered, the component is no longer rendered? Do I need to import the actual Vuex storage?

<template>
  <div>
   <transition name="fade" appear>
     <div ref="modal" class="modal-overlay"
       v-if="isShow"
       @click="close">
     </div>
   </transition>
 <transition name="pop" appear>
  <div class="modal"
       role="dialog"
       v-if="isShow"
  >
  <div class="layer">
      <slot name="content"></slot>
    </div>
  </div>
</transition>
</div>
import { mapState } from 'vuex'

export default {
  name: "VModal",
  computed:{
    ...mapState({
      isShow: state => state.showModal
    })
  },
  methods:{
    close(){
      this.$store.commit('SHOW_OR_HIDE_MODAL', false)
    }
  }
}




import Vuex from "vuex"
import { mount, createLocalVue } from "@vue/test-utils"
import VModal from '../../assets/src/components/VModal'
const localVue = createLocalVue()
localVue.use(Vuex)

describe('testing modal', () => {
let mutations
let state
let store

beforeEach(() => {
    state = {
        showModal: true
    }
    mutations = {
        SHOW_OR_HIDE_MODAL: jest.fn()
    }
    store = new Vuex.Store({ state, mutations })
})
test('check close modal', async () => {
    const wrapper = mount(VModal, {
        store, localVue
    })

    await wrapper.find(".modal-overlay").trigger("click")

    await wrapper.vm.$nextTick();
    expect(wrapper.find(".modal-overlay").exists()).toBe(false)
    expect(wrapper.find(".modal").exists()).toBe(false)
 })
})

I also have an index.js file with the store setup.

While testing, I encountered an error after clicking.

I realize my mistake but struggle with testing Vuex correctly. Apologies for the naive question, any help would be greatly appreciated.

Answer №1

During your test, you have set the state of showModal to true:

beforeEach(() => {
  state = {
    showModal: true
  }
  ...
})

This results in the overlay being displayed, causing your test conditions to evaluate as true.

<div ref="modal" class="modal-overlay"
   v-if="isShow"
   @click="close">
 </div>

The computed value 'isShow' is referencing the showModal = true condition in your test.

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

Ways to extract individual values from a Json Array and utilize them individually

I have a JSON data structure that I need to parse and separate each field into different arrays, so that I can use them individually. For instance, I want to split my data into two rooms: room 1 and room 2. After separating the data, I need to format it a ...

Retrieving the custom attribute value from the chosen option and storing it in a JavaScript variable

I am currently working on a project that involves a country select input, with custom attributes included in the options. My goal is to retrieve the value of the "name" attribute using JavaScript and then append it to a link for further processing. Howev ...

Mapping URLs to objects in JavaScript, TypeScript, and Angular4

I have implemented a class called SearchFilter class SearchFilter { constructor(bucket: string, pin: number, qty: number, category: string) { } } When the user performs a search, I populate the filter i ...

Automate your workflow with Apps Script: Save time by appending a row and seamlessly including additional details to the

I currently have 2 server-side scripts that handle data from an html form. The first script saves user input to the last row available in my Google sheet, while the second script adds additional details to the newly created row. Although both scripts work ...

Tips for utilizing javascript document.createElement, document.body, and $(document) in an HTML web resource for Microsoft CRM code reviews

Let me start off by saying that I am not a regular blogger and I am feeling quite confused. If my question is unclear, please provide guidance for improvement. I recently submitted a Microsoft CRM PlugIn to the Microsoft Code Review. I am new to Javascrip ...

Styling Your Navigation Bar with CSS and Active States

Creating an interactive navigation element for a menu can be challenging, but here's a helpful example. http://jsfiddle.net/6nEB6/38/ <ul> <li><a href="" title="Home">Home</a></li> <li class="activ ...

Connect an Angular Service object to a Controller's Scope and keeping it in sync

I am facing an issue with the interaction between my EmployeeService and EmployeeController. The service contains a specific object which I bind to the controller's scope: app.controller('EmployeeController', function($scope, EmployeeServic ...

"Retrieve a specific object from a JSON file using NextJS based on its ID

NextJs is the framework I am currently utilizing for my project. Is there a way to render a specific project based on its unique ID? { “projects”: [ { "id": 1, "picture": "portf.jpg" }, { ...

What are some strategies for breaking down large components in React?

Picture yourself working on a complex component, with multiple methods to handle a specific task. As you continue developing this component, you may consider refactoring it by breaking it down into smaller parts, resembling molecules composed of atoms (it ...

Employing setTimeout within a repetitive sequence

function displayColors() { $.each(colors, function(index) { setTimeout(function(){ revealColor(colors[index]); }, 1000); }); } I'm attempting to create a loop where the revealColor function is executed every second until all colors ...

The error message "reload is not defined" indicates that the function reload

Initially, I encountered the error TypeError: require(...) is not a function, prompting me to add a semicolon at the end of require("./handlers/slashcommands"). However, this led to a new issue: ReferenceError: reload is not defined. This occurre ...

Are there any options available for customizing the animation settings on the UI-bootstrap's carousel feature?

If you're interested in seeing an example of the standard configuration, check out this link. It's surprising how scarce the documentation is for many of the features that the UIB team has developed... I'm curious if anyone here has experie ...

Prevent scrolling/touchmove events on mobile Safari under certain conditions

iOS 5 now supports native overflow: scroll functionality. I am trying to implement a feature where the touchmove event is disabled for elements that do not have the 'scrollable' class or their children. However, I am having trouble implementing ...

Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code: <html> <head> </head> <body style="text-align:center;" id="body"> <p id="GFG_UP1" style="font-size: 16px;"> </p ...

Tips for clearing text inputs in ReactJS

In my current Reactjs project using nextjs, I am facing an issue with clearing input fields after a click event. Below is the code snippet that I have been working on: <form onSubmit={handleSubmit}> <input type="text" ...

What is the best way to check for a matching array value in my menu list and apply a corresponding class tag to it?

I need a way to dynamically add a class to tags that match specific array values. My menu list consists of 150 items, and I want to add a class to the tag whose text matches an element in the array. <ul class="nav main" id="tabs"&g ...

Disable javascript when using an iPad

I'm working on a website with parallax scrolling that I don't want to function on iPads. Is there a way to prevent the parallax effect from happening when the site is accessed on an iPad? Any guidance on how to disable parallax scrolling based o ...

Using Express.js with Pug.js, dynamically render the page with new content following a fetch POST request

I have a collection of article previews sourced from a database and rendered on the webpage using a Pug.js mixin. each article in articles +articlePreview(article.title, article.text, article.imgSrc) To enhance the user experience, I want to implem ...

Navigating around potential type errors when passing data for chart.js can be challenging. Here are some strategies to

I'm currently working on an application that includes a chart, and I'm facing an issue while trying to populate the chart with data from my store. The error occurs when I attempt to pass the chartData object through props to the data property of ...

Retrieving the output from a nested scope within a function

I have a scenario where I am working with a function that has a nested "then" function containing a return statement. My goal is to combine this inner return data with the outer return data. Below is the code snippet: public async getAllWidgets(): Promis ...