问题
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