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.

https://i.sstatic.net/5eXm6.png

While testing, I encountered an error after clicking. https://i.sstatic.net/bHFRG.png

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

Using JavaScript and jQuery, apply a class when a specific radio button is checked and the data attribute meets certain criteria

Need help with changing explanation color based on correct answer selection in multiple choice question. Currently, all choices turn green instead of just the selected correct one. Any assistance is welcome, thank you. html <li class='test-questi ...

What is the best way to send the input text to the filter component in my React application?

I am currently working on developing an application utilizing the "Rick and Morty API" to display a list of characters with various attributes such as gender, alive status, images, etc. My main goal is to implement a search bar that allows users to search ...

Receiving AssertionError when running unit tests in Vuex comparing to { Object (type, text) }

I've been struggling with unit testing Vuex actions recently, finding it difficult to understand what the tests are actually expecting. I'm following the guidelines on https://vuex.vuejs.org/en/testing.html and using their action helper function. ...

CORS blocked in the live environment

error + whole page As a newcomer to JavaScript, I recently deployed my project. During development, everything was functioning well. However, I am now facing an issue with CORS when attempting to sign in (registration works without any problems, confirmin ...

Utilizing class attributes within multiple classes

I have created a custom class called MutationValidator as follows: const ERR_MSG = 'Error1'; @Service() export class MutationValidator { .. } This class is used in another class like so: import { MutationValidator } from './mutation ...

How do I access the variable value from inside a function in jQuery?

Is it possible to extract the value from 'a = entry.username' outside of the function? I need to retrieve a value that is already being looped inside the function. $('#btnlogin').click(function(){ var usernamelogin = $(&apos ...

What is the best way to ensure complex types are properly initialized and functioning when declaring data within a vue.js module?

Utilizing a TypeScript class that I created called Budget to initialize data for a module has been proving to be challenging. When I attempt something like this: currBudget: {} = { id: 20, name: 'Chris' }; everything functions as expected. How ...

Disable Jquery toolstrip while the menu is open

Currently, I am utilizing the jQuery toolstrip plugin in my project. I have a requirement to disable it whenever the sidebar menu is opened. Below are the HTML codes for my menu with li tags: <div class="sidebar-wrapper" id="sidebar-wrapper"> <ul ...

Implementing Next.js in a live production environment

I've been using next.js for some time now, but I'm still trying to wrap my head around how it operates in a production environment. As far as I understand it, when a request is made to the server, the server retrieves the requested page from the ...

Using JQuery to rebind() after resetting the count

In my game, I have implemented a feature to ensure that the start button can only be clicked once each time it appears in order to prevent the function from loading multiple times. I wrote some code that tracks the number of clicks and unbinds the click e ...

Uncovering a particular property within an array with the help of EJS

I am still learning about ejs and javascript. I have an ejs file where I want to display a list of array objects with unique properties. My goal is to iterate through the array's length, check if a specific property matches a string, and then display ...

What is the best way to send a function along with personalized data?

Currently, I am working on a project using node.js with socket.io. I am looking for a way to have socket.on() use a unique callback function for each client that joins the server. Here is my current technique: I have created a simple JavaScript class whi ...

Can you provide me with instructions on how to create a toggle effect for a button using vanilla JavaScript?

Looking for guidance on creating a toggle effect with a button that switches between 2 images. I've managed to get it working with event listeners on btn2 and btn3, but can't seem to implement the 'toggle' effect on btn1. Any insights o ...

What is the best way to create a floating navigation bar that appears when I tap on an icon?

As a beginner in the realm of React, I recently explored a tutorial on creating a navigation bar. Following the guidance, I successfully implemented a sidebar-style navbar that appears when the menu icon is clicked for smaller screen sizes. To hide it, I u ...

Express file response problems affecting React front-end communication

I am currently developing a basic questionnaire on a React full stack website that uses React, Express, and SQL. Right now, my main goal is to return an error message from React and have it displayed on the front end. This is the code for my express endp ...

What is the best way to include an event listener within the `setup` function?

With the switch to vue3, the $on method has been deprecated. In order to add an event listener, it is now necessary to write it directly on the element itself. <transition name="fade" @after-enter="afterEnter"> <div>foo ...

Obtain the name of the client's computer within a web-based application

I am working on a Java web application that requires the computer name of clients connecting to it. Initially, I attempted to retrieve this information using JavaScript and store it in a hidden form field. However, I discovered that JavaScript does not hav ...

Dynamically remove values from other fields in a React Formik form based on checkbox conditions

Currently, I am utilizing react-formik for my form implementation. I have encountered an issue with checkbox-based conditions where the checked status of a checkbox determines whether two hidden fields are displayed or hidden. If the user checks the checkb ...

The error message states that `article.createdAt.toLocalDateString` is not a valid

const mongoose = require("mongoose"); const blogPostSchema = new mongoose.Schema({ title: String, image: String, description: String, createdAt: { type : Date, default : new Date() } }); const blogPos ...

Encountering a NoSuchElementException when transitioning from frame[0] to window[1] in Firefox GeckoDriver using Selenium with Python

Encountered an issue with the Firefox GeckoDriver browser where I receive an error stating `element not found`. The problem arises when I navigate from window[1] to frame[0], back to window[1], and then attempt to click the close frame button. I prefer u ...