如何使用 vuex-test-utils 测试组件中的 VueX 状态变化?
How to test VueX state change in the component using vuex-test-utils?
我有一个非常简单的组件,它依赖于从后端加载到商店中的数据,我想为此流程编写一个单元测试。
基本上,我的模板代码是:
<div class="my-component">
<div class="loading-screen" v-if="loading"></div>
<div class="content" v-if="!loading"></div>
</div
加载是来自商店的计算值。
我想用以下测试场景来测试它:
describe('My Component', () => {
let wrapper;
let actions;
let store;
let state;
let mutations;
beforeEach(() => {
actions = {};
state = {
loading: true,
};
mutations = {
finishLoading: (state) => { state.loading = false },
};
store = new Vuex.Store({
modules: {
myModule: {
namespaced: true,
state,
actions,
mutations,
}
}
});
});
test('Calls store action for data and then shows the page', () => {
wrapper = mount(MyComponent, { store, localVue });
expect(wrapper.find('.loading-screen').isVisible()).toEqual(true);
expect(wrapper.find('.content').exists()).toEqual(false);
store.commit('finishLoading');
expect(wrapper.find('.loading-screen').exists()).toEqual(false);
expect(wrapper.find('.content').isVisible()).toEqual(true);
});
});
store.commit('finishLoading')之后的部分失败。如何触发组件根据商店数据更新?
尝试在store.commit('finishLoading')之后添加这一行。
await wrapper.vm.$nextTick();
并且记得让你的函数 async.
test('Calls store action for data and then shows the page', async () => {
后来我发现我还漏掉了一件事!
我的商店是 namespaced,所以很自然地,因为我没有为它创建 NamespacedHelper,所以我需要调用以下 mutation:
store.commit('applicationApply/finishLoading');
这是对上述有效修复的补充,解决了主要问题。
我有一个非常简单的组件,它依赖于从后端加载到商店中的数据,我想为此流程编写一个单元测试。 基本上,我的模板代码是:
<div class="my-component">
<div class="loading-screen" v-if="loading"></div>
<div class="content" v-if="!loading"></div>
</div
加载是来自商店的计算值。 我想用以下测试场景来测试它:
describe('My Component', () => {
let wrapper;
let actions;
let store;
let state;
let mutations;
beforeEach(() => {
actions = {};
state = {
loading: true,
};
mutations = {
finishLoading: (state) => { state.loading = false },
};
store = new Vuex.Store({
modules: {
myModule: {
namespaced: true,
state,
actions,
mutations,
}
}
});
});
test('Calls store action for data and then shows the page', () => {
wrapper = mount(MyComponent, { store, localVue });
expect(wrapper.find('.loading-screen').isVisible()).toEqual(true);
expect(wrapper.find('.content').exists()).toEqual(false);
store.commit('finishLoading');
expect(wrapper.find('.loading-screen').exists()).toEqual(false);
expect(wrapper.find('.content').isVisible()).toEqual(true);
});
});
store.commit('finishLoading')之后的部分失败。如何触发组件根据商店数据更新?
尝试在store.commit('finishLoading')之后添加这一行。
await wrapper.vm.$nextTick();
并且记得让你的函数 async.
test('Calls store action for data and then shows the page', async () => {
后来我发现我还漏掉了一件事! 我的商店是 namespaced,所以很自然地,因为我没有为它创建 NamespacedHelper,所以我需要调用以下 mutation:
store.commit('applicationApply/finishLoading');
这是对上述有效修复的补充,解决了主要问题。