How to mock a Vuex store in VueJS test-utils parentComponent

我与影子孤独终老i 提交于 2019-12-20 07:24:13

问题


I'm using Jest with vue-test-utils trying to test if a child component reacts to an $emit event in the parent component.

VueJS test-utils library provides a parentComponent option to be passed when mounting/shallow mounting the component.

Everything is working fine except that even though I instantiate the component with a mocked Vuex store, the parent component throws a

TypeError: Cannot read property 'state' of undefined

on a this.$store.state.something.here piece of code in the parent component.

How can I mock the Vuex store there?

The component mount looks like this:

const wrapper = shallowMount(ChildComponent, {
  store,
  localVue,
  parentComponent: ParentComponent,
  mocks: {
    $t: msg => msg,
  },
});

Any ideas on how to solve this?


回答1:


Tried the solution Richard proposed but without much success, even though his guess was right.

The solution was far simnpler than I envisioned, I just stopped instantiating the Vuex.Store and just have the mocked $store in vue-test-utils config like so:

import { createLocalVue, shallowMount, config } from '@vue/test-utils';

config.mocks.$store = {
  state: {
    user: {
      sexy: true
    },
  },
};

I had no need to use an actual instance of Vuex as I only needed to mock the actual data so this worked perfectly.




回答2:


How are you creating the mock store? It should be something like

const storeOptions = {
  state: {...},
  getters: {...},
  mutations: {...}
}
const mockStore = new Vuex.Store(storeOptions)

Since this.$store is undefined, I suspect you might just be passing the options object to shallowMount.



来源:https://stackoverflow.com/questions/52477645/how-to-mock-a-vuex-store-in-vuejs-test-utils-parentcomponent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!