【问题标题】:Mocking just part of getters when importing the global store导入全局商店时仅模拟部分吸气剂
【发布时间】:2021-10-04 20:24:08
【问题描述】:

知道是否可以仅模拟全局存储中的 getter 吗?

我试过这段代码,但它不起作用:

import store from '@/store';
import Vuex from "vuex";

const localVue = createLocalVue();
localVue.use(VueRouter);
localVue.use(Vuex);

const wrapper = mount(App, {
      mocks: {
        $store: {
          getters: {
            isLoggedIn: () => true // This is always returning false. I need this getter to return true value
          },
        }
      },
      store, // this is the global store for my application
      localVue,
      router,
    });

【问题讨论】:

    标签: vuejs2 vuex vue-test-utils


    【解决方案1】:

    在不调用localVue.use(Vuex) 和不创建store 实例的情况下安装组件时使用mocks 属性会容易得多:

    const wrapper = mount(App, {     
      localVue,
      router,
      mocks: {
        $store: {
          getters: {
            isLoggedIn: () => () => true,
          }
        } 
      }
    });
    
    

    【讨论】:

    • 是的,这样好多了。我还是 vuejs 的新手 :)
    • 很高兴代码有帮助! :) 顺便说一句,有一本很好的关于测试 Vue 应用程序的书——Edd Yerburgh 的《测试 Vue.js 应用程序》
    【解决方案2】:

    我从 Vue 测试手册示例 here 中获得灵感解决了我的问题。

    import * as otherNameThanStore  from '@/store'; // we need to change the name to anyone other than store
    import Vuex from "vuex";
    
    const localVue = createLocalVue();
    localVue.use(VueRouter);
    localVue.use(Vuex);
    
    const store = new Vuex.Store( // attribute name must be store, otherwise typescript will throw this error: is not assignable to parameter of type 'FunctionalComponentMountOptions<Vue>'
      {
      state: {
        ...otherNameThanStore.default.state
      },
      getters: {
        ...otherNameThanStore.default.getters,
        isLoggedIn: (state) => () => true,
      },
    }
    )
    
    const wrapper = mount(App, {     
          store,
          localVue,
          router,
        });
    

    希望它可以帮助其他人:)

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      相关资源
      最近更新 更多