2

I'm new to testing and I'm trying to set up first unit tests with vue-test-utils(jest). I wanted to write first simple test, just check whether a component is a Vue instance, but I'm getting an error, which I don't really understand. It seems my test tries to go through the component and fails, because it can't read $store.state I'm using computed properties which come from vuex state. The component works fine and imports everything correctly. What am I missing here? I also tried to mock the store, but it didn't help. I have ts-jest, vue-jest, jest, @types/jest and @vue/test-utils installed.

my jest configuration in package.json:

    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
      "js",
      "ts",
      "json",
      "vue"
    ],
    "transform": {
      ".*\\.(vue)$": "vue-jest",
      "^.+\\.tsx?$": "ts-jest"
    },
    "testURL": "http://localhost/"
  }
}

my test file:

import Login from '../Login.vue'
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'

const localVue = createLocalVue()

localVue.use(Vuex)

describe('Login.vue', () => {
  let state: any;
  let store: any;

  beforeEach(() => {
    state = {
      errorMsg: jest.fn(),
      error: jest.fn()
    }
    store = new Vuex.Store({
      state
    })
  })

  it('is a Vue instance', () => {
    const wrapper = mount(Login, { store, localVue })
    expect(wrapper.isVueInstance()).toBeTruthy()
  }) 
})
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
p-sara
  • 329
  • 3
  • 16

1 Answers1

0

This stackoverflow question TypeError: Cannot read property 'getters' of undefined

helped me to solve my issue. I changed computed written like this:

get loginErrorMsg() { return this.$store.state.auth.errorMsg; }

and used mapState from vuex instead like below, and it worked like a charm.

@Component({
  computed: {
    ...mapState(["errorMsg", "token"])
  }
})
export default class Login extends Vue {...}
p-sara
  • 329
  • 3
  • 16