TypeError: Cannot read property 'getters' of undefined
Asked Answered
C

3

8

I'm trying to test a basic Vue Component that makes reference to a Vuex store. I thought I followed Vue's example (https://vue-test-utils.vuejs.org/guides/using-with-vuex.html#mocking-getters) to a T but it doesn't appear to be working.

I get the error that is mentioned in the title.

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

describe('Navbar.vue', () => {
  let store: any
  let getters: any

  beforeEach(() => {
    getters: {
      isLoggedIn: () => false
    }

    store = new Vuex.Store({
      getters
    })
  })

  it('renders props.title when passed', () => {
    const title = 'Smart Filing'
    const wrapper = shallowMount(Navbar, {
      propsData: { title },
      i18n,
      store,
      localVue,
      stubs: ['router-link']
    })

    expect(wrapper.text()).to.include(title)
  })
})

I'm using class components so maybe that has something to do with it?

@Component({
  props: {
    title: String
  },
  computed: mapGetters(['isLoggedIn'])
})
export default class Navbar extends mixins(Utils) {}

Thanks in advance.

Converge answered 5/2, 2019 at 1:23 Comment(1)
Does your getter happen to be namespaced?Prevalent
C
4

Figured it out.

When you declare the getter in the component, make sure to define the variable that is going to be used.

@Component({
  props: {
    title: String
  },
  computed: mapGetters(['isLoggedIn'])
})
export default class Navbar extends mixins(Utils) {
  isLoggedIn!: boolean <== I did not have this before. 
  ...
}

Edit: Also, I wasn't actually using the mock getter in the test so you don't even need to mock the store. All you need to do is declare that variable on the component.

Converge answered 5/2, 2019 at 17:41 Comment(0)
P
2

The "getters" here is not properly assigned:

  beforeEach(() => {
    getters: {
      isLoggedIn: () => false
    }

    store = new Vuex.Store({
      getters
    })
  })

It should be getters = {... rather than getters: {... because your argument to beforeEach is a function and not an object.

I can confirm that it is indeed correctly written in the documentation.

Good luck!

Paginal answered 5/2, 2019 at 3:15 Comment(2)
Good catch, but unfortunately it's still not workingConverge
Is it written in the docs like that? vuex.vuejs.org/guide/getters.htmlWine
J
0

For me, this error message came up when I was attempting to load two different store instances that were both importing the same module. By default, Vuex assumes a single store. Something wonky was going on, and this error was the result.

Jerrelljerri answered 2/9, 2021 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.