首页 > 解决方案 > Jest Vuex:创建的钩子出错:“TypeError:无法读取未定义的属性'dispatch'”

问题描述

我目前正在尝试模拟在created()Vue 挂钩中调用的两个 Vuex 操作,但是,Jest 不断返回"TypeError: Cannot read property 'dispatch' of undefined",这是我尝试过的:

测试文件:

    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()

组件文件:

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

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

请任何人都可以建议我在这里做错了什么,我已经尽我所能,但由于 created() 钩子错误,测试仍然失败。

标签: vue.jsjestjsnuxt.jsvuex

解决方案


我已经解决了,我出错的地方是包装器中的,应该是(注意花括号中的差异)

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

推荐阅读