Jest Vuex: Error in created hook: "TypeError: Cannot read property 'dispatch' of undefined"

Viewed 1276

I am currently trying to mock out the two Vuex actions that is called in the created() Vue hook, however, Jest keeps returning "TypeError: Cannot read property 'dispatch' of undefined", this is what I have tried:

Test file:

    let store
    let actions

    beforeEach(() => {
      actions = {
        setApiUrl: jest.fn(),
        init: jest.fn()
      }

      store = new Vuex.Store({
        modules: {
          membership: membershipTestData
        },
        actions
      })
    })

    const wrapper = shallowMount(
      Component,
      store,
      localVue
    )

    await wrapper.vm.setApiUrl('')
    await wrapper.vm.init()

    expect(actions.setApiUrl).toHaveBeenCalled()
    expect(actions.init).toHaveBeenCalled()

Component file:

  created () {
    this.setApiUrl('')
    this.init()
  },

  methods: {
    ...mapActions('membership', ['init', 'setApiUrl'])
  }

Please can anyone suggest what I am doing wrong here, I have tried everything I could, but the test still fails due to the created() hook error.

1 Answers

I have solved it, where I went wrong was the in the wrapper, which should be (notice the diff in curly brace)

const wrapper = shallowMount(Component, {
  localVue,
  propsData
})
Related