Tips for updating Vuex getter value during Vue testing?

I'm working on a simple test scenario where I have the following code:

describe('App', () => {
    let store;
    beforeEach(() => {
        store = new Vuex.Store({
            modules: {
                auth: {
                    namespaced: true,
                    getters: {
                        isLoggedIn: () => true,
                    }
                }
            }
        });
    });

    test('App hides navbar when user is logged in', () => {
        const wrapper = shallowMount(App, { store, localVue });
        expect(wrapper.contains(Nav)).toBe(false);
// store.getters['auth/isLoggedIn'] = () => false; // Not possible
    });
});

However, I am encountering an issue as I can't modify the getter value and receiving the following error in the console:

TypeError: Cannot set property auth/isLoggedIn of # which has only a getter

Can anyone suggest how should I go about setting the getter value in my test?

Answer №1

To make changes to the getter value, you can refer to the code provided below.

let currentValue = store.getters['auth/isLoggedIn']
console.log('currentValue', currentValue) // currentValue = true

expect(store.getters['auth/isLoggedIn']).toBe(true)

  store = {
    getters: {
      'auth/isLoggedIn': !currentValue
    }
  }

  let updatedValue = store.getters['auth/isLoggedIn']
  console.log('updatedValue', updatedValue)  //updatedValue = false

  expect(store.getters['auth/isLoggedIn']).toBe(false)

Answer №2

According to the guidelines provided by Vue-test-utils

  1. Begin by importing getters from the store. For example:

import Getters from '../../../src/components/Getters'

  1. Substitute getters for App

const wrapper = shallowMount(App, { store, localVue });

I trust this information proves valuable.

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

Center a sans-serif font vertically with exact precision while adjusting the font size

My issue is an expansion of a previous problem I mentioned in another question, which can be found here Vertically align sans-serif font precisely using jquery/css. To summarize: I am aiming to align two divs containing text, with one positioned above the ...

Is there a way in Python to translate JavascriptSerializer into a datetime object?

My JSON file contains date and time in the format generated by JavascriptSerializer, shown below: {"StartDate": "/Date(1519171200000)/", "EndDate": "/Date(1519257600000)/",} How can I convert it to datetime formats like these? "2012-04-23T18:25:43.511Z" ...

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

After encountering a character with CSS, begin a new line

I have a CSV spreadsheet with data that looks like this: <p>Features:• first feature• second feature• third feature• fourth feature• and so on (the total number of features is variable)</p> I want each feature to display on a new li ...

Do not jest about neglecting to close the expressJS server while running on AWS CodeBuild

While successfully exiting when running locally, Jest fails to exit when run on CodeBuild and shows the following error: Jest has identified a single open handle that may prevent Jest from exiting: ● TCPSERVERWRAP 13 | routes(app) 14 | > 1 ...

You should be providing a string value as expected. It seems that you may have overlooked exporting your component from the correct file it was defined in, or perhaps there is confusion with default and named

I encountered a strange error despite meticulously organizing and exporting/importing files. The code is structured from components to the App render method. Item.js import React from 'react'; import './Global.css' const Item = ({data ...

The script from '*' is being denied execution because its MIME type ('application/json') is not executable, and a strict MIME type check is in place

Here is the code I used to retrieve data from the confluence rest api: <script type="text/javascript" src="Scripts/jquery.min.js"></script> <script> $.ajax({ type: "GET", url: "https://blog.xxxxx.com/rest/api/content? ...

How can you assign a unique number to each item within the same category in order to differentiate them?

const productData = [ {size: 1180160, category: "Keswick", index: 1}, {size: 1059328, category: "HCOPA", index: 2}, {size: 30720, category: "HCOPA", index: 3}, {size: 493056, category: "Darhan Saluja", index: 4}, {size: 267776, category: "CRSA", index ...

Error encountered when attempting to retrieve posts using Axios: Unexpected symbol detected, expected a comma (25:4)

I've been working on implementing an axios getPosts function, but I keep encountering a syntax error that I can't seem to locate in my code. getPosts = async () => { let data = await api.get('/').then(({ data }) => data); ...

Covering Vue methods with Jest and Coverage: a comprehensive guide

My goal was to improve the code coverage percentage by covering specific if statements within Vue methods. I am using package versions @vue/test-utils:"^1.1.4" and vue: "^2.6.12". Below is a snippet of my component: <template> <div :class=& ...

Is a Selenium loop a viable option?

</head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">test</td></tr> </thead><tbody> <tr> <td>click& ...

Display a limited number of characters along with a button on the blog tag pages. Clicking on the button will reveal the complete text description

Hey, I am looking to replicate the way WooCommerce tags descriptions are displayed on my WordPress blog. I want it to show only a certain number of characters with a "show all" link, similar to how it appears on this site: I have found some code that work ...

The component is unable to access VueJS references

Below is a simplified version of the code I am working with: <html> <head> <script src="file:///D:/OtherWork/javascript/vue/vue.js"></script> </head> <body> <div id="app"> & ...

Trouble with AJAX request when trying to connect to a distant server

I am facing an issue with my AJAX request. When I test it on localhost, everything works perfectly fine. However, when I upload the code to a remote server, the request fails without any error messages. Even after checking in Firefox and Chrome, there ar ...

Stop dropdown from closing when clicking outside of it

Is there a way to prevent a CDropdown from closing automatically when I click outside of it? I need this functionality so that I can copy text from somewhere and paste it into the CInput field inside the dropdown. Any suggestions on how to achieve this w ...

Google maps are failing to display on the page when loading via ajax

When I click a button, I use AJAX to load a page, but the map on the loaded page is not displaying. There are no errors showing up either. I have tried adding initmap() after the ajax load, but it doesn't work. Do I need to bind it somehow? What am I ...

Issue with React Router functionality not functioning

I am currently facing an issue with my react-router setup. You can find the code I am using by visiting this link - https://github.com/rocky-jaiswal/lehrer-node/tree/master/frontend Although it is a basic setup for react-router, I am experiencing difficu ...

Creating a dual-column checkbox design with CSS only

I'm working with a dynamically generated form element that can only be styled using CSS. I need help achieving a specific layout without making any HTML changes, except for the classes. The "element" and "formField" classes are common and cannot be mo ...

Rephrase the ajax call and the data retrieved

I'm struggling to find a solution for writing this code snippet without using async: false,. var imageX; var groupX; $.ajax({ type:'GET', url:'php/myphp.php', dataType:'json', async: false, success: ...

What is the best way to enable my search function to filter out specific items from a table?

Currently, I have created a table populated with data fetched from a JSON file. Now, my focus is on implementing a search functionality that filters out items based on user input and displays only those table rows matching the search criteria. The code sni ...