导入全局商店时仅模拟部分吸气剂

Mocking just part of getters when importing the global store

知道是否可以从全局商店中仅模拟一个 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,
    });

我从 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,
    });

希望对其他人有帮助:)

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

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