Teos Verdi
Teos Verdi

Reputation: 85

Vuex+Jest test fails with TypeError

I am trying to test Vuex store modules on my application, but it keeps returning TypeError: Cannot read property 'getters' of undefined no matter what i try. Please, help. Here's the code:

store/index.ts:

import Vuex from 'vuex';

import auth from './auth';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    auth,
  },
});

store/auth.ts:

export default {
  state: {
    isLoggedIn: getKey(),
  },
  namespaced: true,
  mutations: {
    setLoginState(state: any, isLoggedIn: boolean) {
      state.isLoggedIn = isLoggedIn;
    },
  },
  actions: {
   // Stuff
  },
};

store/__tests__/auth.ts:

import auth from '../auth';

describe('Auth.ts', () => {
  describe('Mutations', () => {
    test('setLoginState sets isLoggedIn correctly', () => {
      const state = {
        isLoggedIn: false,
      };
      auth.mutations.setLoginState(state, true);
      expect(state.isLoggedIn).toBe(true);
    });
  });
});

packages used:

    "vue": "^2.5.22",
    "vuex": "^3.1.0",
    "webpack": "^4.29.0"
    "jest": "^23.6.0",
    "ts-jest": "^23.10.5",

Upvotes: 1

Views: 471

Answers (1)

Teos Verdi
Teos Verdi

Reputation: 85

I've found the problem. The issue is that auth.ts was importing axios instance, which wasn't mocked. Removing actions, that require axios calls or adding jest.mock('API_PATH', jest.fn); to test resolves the issue.

Upvotes: 2

Related Questions