''$store' is undefined when running jest test with vuex-oidc

When testing a component the checks a OpenID response, this is the following error I get returned:

TypeError: Cannot read property '$store' of undefined

  at mappedAction (node_modules/vuex/dist/vuex.cjs.js:1273:27)
  at src/views/OidcCallback.vue:599:7

This happens after I call a function inside a module which I retrieve from a mapActions-call like this:

const { oidcSignInCallback } = mapActions("oidcStore", [
  "oidcSignInCallback",
]);

Is there anyone that also encountered this issue? And is there a way to reference the mapActions-function to the mocked store? Because at the moment it references to the store that is generated in the main.ts.



Solution 1:[1]

There are different ways to solve this for Vue 2.

One method is to use the Jest setup.js file

jest.config.js

module.exports = {
  ...
  setupFilesAfterEnv: ['./tests/setup.js'],
  ...
}

And the setup file

import { config } from '@vue/test-utils'
config.mocks.$store = { dispatch: jest.fn(), getters: {} }

The unit test could look like this.

import { mount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import VueComponent from '@/components/path/to/MyComponent.vue'

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

describe('MyComponent', () => {
  it('is a Vue instance', () => {
    const wrapper = mount(VueComponent, {
      localVue,
      propsData: {}
    })

    expect(wrapper.exists()).toBe(true)
  })
})

Alternatively, the mocks for the store could be added to the test

import { mount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import VueComponent from '@/components/path/to/MyComponent.vue'

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

const user = {
  namespaced: true,
  getters: {
    userName: jest.fn(),
  },
  actions: {
    userUpdateName: { handler: jest.fn() },
  },
}
let store = new Vuex.Store({ // the mocked store
    modules: {
      user // the modules here if needed
    },
})
store.dispatch = jest.fn()

describe('MyComponent', () => {
  it('is a Vue instance', () => {
    const wrapper = mount(VueComponent, {
      localVue,
      store,
      propsData: {}
    })

    expect(wrapper.exists()).toBe(true)
  })
})

Alternatively, we can use a mock directly in the test

import { mount } from '@vue/test-utils'
import Vuex from 'vuex'
import VueComponent from '@/components/path/to/MyComponent.vue'

describe('MyComponent', () => {
  it('is a Vue instance', () => {
    let mocks = {
        $store: { dispatch: jest.fn(), getters: {} }
    }
    const wrapper = mount(VueComponent, {
      mocks,
      propsData: {}
    })

    expect(wrapper.exists()).toBe(true)
  })
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1