Tanmay
Tanmay

Reputation: 3159

How to change vuex getter value in vue testing?

I have this simple test:

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
    });
});

But I can't change the getter value and I am seeing this error in the console:

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

How do I set the getter value in my test?

Upvotes: 1

Views: 3145

Answers (2)

BS Sushmitha
BS Sushmitha

Reputation: 21

Refer to the code mentioned below. That's how you can modify the getter value.

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

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

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

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

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

Upvotes: 2

Varit J Patel
Varit J Patel

Reputation: 3520

As per the documentation of Vue-test-utils

  1. Import getters from the store. e.g

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

  1. Place getters instead of App

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

Hope this helps.

Upvotes: 1

Related Questions