如何使用vuex-test-utils测试组件中的VueX状态更改?

时间:2020-03-11 13:11:00

标签: vue.js vuex vue-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')之后的部分失败。如何触发组件根据商店数据进行更新?

2 个答案:

答案 0 :(得分:1)

尝试在 store.commit('finishLoading')之后添加此行。

await wrapper.vm.$nextTick();

请记住使您的功能异步

test('Calls store action for data and then shows the page', async () => {

答案 1 :(得分:0)

后来我发现我也错过了一件事! 我的商店是 namespaced ,所以自然地,因为我没有为其创建NamespacedHelper,所以我需要调用以下突变:

store.commit('applicationApply/finishLoading');

这是对上述有效修复程序的补充,可以解决主要问题。