Examining Vuex Mutations using Jest confirms no alteration in state

I am currently facing an issue with testing a namespaced Vuex module using Jest. Despite making mutations to the mocked state, I am not seeing any changes reflected.

Below is the code for my addEvents mutation:

   addEvents: (state, infos) => {
      try {
        state.events = state.events.concat(infos);
      } catch (error) {
        console.error("[ERR vuex event set] ", e.message);        
      }

The test file is named event.test.js and contains the following code snippet:

import { createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
//store
import event from '../index.js'

const localVue = createLocalVue();
localVue.use(Vuex);

describe('event', () => {
  //intial state
  const state = {
    events: []
  }

  const newEvent = {
    text: 'Hello',
    eventCode: 'importantEvent'
  }

  //mutate
  event.commit('event/addEvents', newEvent);
  expect(state.events).toContainEqual(newEvent)
})
})

I have ensured that I am importing from the correct store index which includes multiple modules. However, when attempting to import the specific module for testing, my mutations are not being found by the test.

Upon running Jest, the output displays the following error message:

 FAIL  vue/vuex/modules/event.test.js
  ● event › encountered a declaration exception

    expect(received).toContainEqual(expected) // deep equality

    Expected value: {"eventCode": "importantEvent", "text": "Hello"}
    Received array: []

      20 |   //mutate
      21 |   event.commit('event/addEvents', newEvent);
    > 22 |   expect(state.events).toContainEqual(newEvent)
         |                        ^
      23 | })

      at Suite.<anonymous> (vue/vuex/modules/event.test.js:22:24)
      at Object.<anonymous> (vue/vuex/modules/event.test.js:9:1)  

Answer №1

I am grateful to Estus Flask for assisting me in resolving the issue I had with not referencing the store correctly. The code below is now functioning as intended, including my reset route which was already in place. I have also updated my event import to be named 'store' for better clarity.

import { createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
// Importing store
import store from '../index.js'

const localVue = createLocalVue();
localVue.use(Vuex);


describe('event mutations', () => {
  beforeEach(() => {
    // Resetting state before each test
    store.commit("event/reset");
  });

  it('adding events works', () => {
    const newEvent = {
      text: 'Hello',
      eventCode: 'importantEvent'
    };
  
    // Mutating
    store.commit('event/addEvents', newEvent);
    expect(store.state.event.events).toContainEqual(newEvent);
  });

  it('store resets properly between tests and reset works', () => {
    expect(store.state.event.events).toHaveLength(0);
  });
})

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

Is there a way to stylize the initial words of a brief text block by blending small caps with italics, all while avoiding the use of a span tag?

I have a series of images with numbered captions like "Fig. 1", "Fig. 2", "Fig. 3", followed by a brief description on the same line. Is there a way to programmatically style these strings (the “Fig. #” only) using CSS or Javascript to make them italic ...

Setting URL parameters dynamically to the action attribute of a form using JavaScript code

I'm having trouble posting Form data to my Server. I am dynamically setting the element and its URL parameters for the action attribute, but it seems like it's not recognizing those attributes. Can you help me figure out what I'm doing wrong ...

Angular single page application with a sleek, user-friendly navigation bar for easy browsing

I have been attempting to solve the issue at hand without much success. As a newcomer to web development, I have been working on creating a basic app using angularjs and bootstrap. My pages are fairly sparse, consisting only of a few inputs and buttons t ...

Learning the ins and outs of Node.js: Creating a client to connect to a Node.js server and receive broadcast messages

In implementing my nodeJS Server, everything seems to be running smoothly. However, now I am looking to create a client that can receive messages from the server and trigger specific JavaScript functions based on those messages. The process involves: Us ...

Disabling GPS with HTML5/phonegap: A step-by-step guide

Looking to create a function that can toggle GPS on and off for both iPhone and Android devices ...

The functionality of loading JSON is not working properly in ePub3

Currently, I am working on a project involving the creation of an ePub3 eBook. One of the exciting features I have successfully integrated is three.js to showcase some models. My next goal is to develop 'hotspot' elements (small cubes that users ...

invisible recaptcha with synchronous ajax

Hey, I'm trying to figure out a solution on how to obtain the token or a valid response from Recaptcha and then proceed with running the ajax call. Does anyone have any suggestions on how to achieve this in a synchronous manner? Here's the proce ...

This element is not compatible for use as a JSX component

I have created a React component which looks like this import React from 'react'; import { ECOTileSummary } from './ECOTileSummary'; import { TileSummary } from './TileSummary'; interface SuperTileSummaryProps { date?: s ...

Ways to retrieve a file from a specific location using fetch/axios?

For my research, I need to utilize certain network APIs such as fetch or axios to access a local file without using the fs module or importing them directly. I attempted to use both fetch and axios but found that they do not support fetching local files, ...

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

Could there be a mistake in the way array combinatorics are implemented in JavaScript?

Having encountered the necessity for generating unique combinations when dealing with multiple arrays, I developed this script. While it functions as intended during the combination process, storing the result in a final array yields unexpected outcomes. ...

Using the div id within JavaScript to create a new Google Maps latitude and longitude

Here is my code for locating an IP using Google Maps. I am trying to set new google.maps.LatLng('< HERE >') to <div id="loc"></div>. How can I achieve this where the result will be 40.4652,-74.2307 as part of #loc? <scrip ...

The functioning of invoking JavaScript confirm from the code behind is experiencing issues

Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click Dim ResourceObject As Object Dim js As [String] = (vbCr & vbLf & " if(confirm('Are you sure you want to delete from th ...

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

Guide on debugging Express.js server code on Node with Visual Studio Code by Attaching to a live process

Here is a list of the tools I have: Latest Visual Studio Code Express js Node js Take a look at my Attach configuration below: { "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": ...

Create a customizable Tree structure that includes checkboxes for each item and features drag

I am currently working on incorporating a Tree view with checkboxes and drag & drop functionality in Vue. However, I am unsure of where to begin. While I have successfully implemented checkboxes, I am struggling to figure out how to enable the feature whe ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

How can I troubleshoot the unresponsive remove div function on my website?

My code is running fine on CodePen (link provided below), but for some reason, it's not working properly in the web browser. I am executing the code from localhost and the button isn't responding as expected. CODE Here is my Visual Studio code ...

Utilizing Bootstrap Modal functionality in a Django web application to enhance user experience

I am currently facing a minor issue in my Django application. I am attempting to utilize a modal from Bootstrap 4 along with AJAX to create a new object. Below you can view the code I used. However, when the user clicks the button, instead of seeing the mo ...

Retrieve all the records from the collection that have a specific reference number in their ID field

Is it feasible to pull together all documents with an ID that includes a specific value? I am working with Angular 7. I attempted using db.collection('items').where.. but unfortunately, this method is not supported. For instance: (collection) ...