【问题标题】:How to test VueX state change in the component using vuex-test-utils?如何使用 vuex-test-utils 测试组件中的 VueX 状态变化?
【发布时间】:2020-06-23 11:39:13
【问题描述】:

我有一个非常简单的组件,它依赖于从后端加载到存储中的数据,我想为此流程编写一个单元测试。 基本上,我的模板代码是:

    <div class="my-component">
        <div class="loading-screen" v-if="loading"></div>
        <div class="content" v-if="!loading"></div>
    </div

Loading 是来自存储的计算值。 我想用下面的测试场景来测试它:

    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') 之后的部分失败。如何根据商店数据触发组件更新?

【问题讨论】:

    标签: vue.js vuex vue-test-utils


    【解决方案1】:

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

    store.commit('applicationApply/finishLoading');
    

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

    【讨论】:

      【解决方案2】:

      尝试在store.commit('finishLoading')之后添加这一行

      await wrapper.vm.$nextTick();
      

      记得让你的函数异步

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

      【讨论】:

        猜你喜欢
        • 2019-05-28
        • 2021-02-17
        • 1970-01-01
        • 2018-01-20
        • 1970-01-01
        • 2018-10-21
        • 1970-01-01
        • 1970-01-01
        • 2018-05-04
        相关资源
        最近更新 更多