【问题标题】:Vuex mock store undefined in Jest unit testVuex 模拟存储在 Jest 单元测试中未定义
【发布时间】:2020-02-11 08:26:08
【问题描述】:

我是 jest 的新手,正在尝试编写一个依赖于 store 属性值的单元测试。

我试图在我的测试中创建一个新的模拟存储(我已经有一个模拟存储用于不同的测试),但由于某种原因,我不断收到错误

TypeError: Cannot read property 'state' of undefined

我的测试是:

import { shallowMount, createLocalVue,} from '@vue/test-utils';
import userButtons from '@components/user-profile/UserButtons.vue';
import Vuex from 'vuex';
import { defaultValues, } from '@store/api/userButtons.js';

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

describe('UserButtons', () => {
    let actions; 
    let store;
    let storeIsAdded;
    
    beforeEach(() => {
    actions = {
        getUserInfo: jest.fn(),
    };
    store = new Vuex.Store({
        modules: {
        userButtons: {
            namespaced: true,
            actions,
            state: {
            userButton: defaultValues,
            },
            mutations: {
            setUserButton: jest.fn(),
            },
        },
        },
    });
    storeIsAdded = new Vuex.Store({
        state: {
        isItemAdded: true,
        },
    });
    });
    test('vuex called on create', () => {
    shallowMount(UserButtons, { store, localVue, propsData: { id: 3406304, }, });
    expect(actions.getUserInfo).toHaveBeenCalled();
    });

    test('renders correctly', () => {
    const wrapper = shallowMount(UserButtons, { store, localVue, propsData: { id: 3406304, }, });
    expect(wrapper.element).toMatchSnapshot();
    });

    test('indicates remove if isItemAdded is true', () => {
    const wrapper = shallowMount(UserButtons, { storeIsAdded, localVue, propsData: { id: 3406304, }, });
    expect(wrapper.find('.button-action.my-items').text()).toBe('- Remove from My Items');
    });
});

前两个测试通过了。

最后一个测试,'indicates remove if isItemAddedis true, is the one that fails, and is using the mock store,storeIsAdded`。

如果有人有任何见解,将不胜感激!!!

编辑:

即使我将我的模拟商店修改为更类似于似乎正在运行的商店,如下所示:

storeIsInList = new Vuex.Store({
    modules: {
    userButton: {
        namespaced: true,
        actions,
        state: {
        userButton: {
            isItemAdded: true,
        },
        },
    },
    },
});

我得到同样的错误。

【问题讨论】:

标签: vue.js jestjs vuex


【解决方案1】:

似乎错误是在访问组件中的存储状态时出现的。所以,我的猜测是商店可能需要模块/命名空间,即

storeIsInList = new Vuex.Store({
  modules: {
    userButtons: {
      namespaced: true,
      actions,
      state: {
        userButton: {
          isItemAdded: true,
        },
      },
    },
  },
});

正如@il0v3d0g 所说,命名空间名称可能是错误的。

【讨论】:

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