简单地测试带有嘲笑的vue组件会失败

时间:2020-06-18 10:06:49

标签: javascript vue.js jestjs vuex

我第一次使用笑话,并且在开始大量测试之前,我试图使我正常运行。 一开始我只是为此测试:

import { mount, createLocalVue } from '@vue/test-utils';
import VueRouter from 'vue-router';
import Vuex from 'vuex';
import BootstrapVue from 'bootstrap-vue';
import UsersList from './../../components/users/UsersList.vue';

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


describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = mount(UsersList, {
      localVue
    })
    expect(wrapper.contains('div')).toBe(true)
  })
})

最后,它应该成功通过,因为我当然在组件中使用了div。

但是现在的问题是Vuex,或者我不知道。似乎这玩笑无法处理我的vuex $ store.state引用。 TypeError: Cannot read property 'state' of undefined 在那之后: [Vue warn]: Error in render: "TypeError: Cannot read property 'resolve' of undefined"

我的配置如下:

jest.config.js:

/* eslint-disable no-undef */
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
  verbose: true,
  moduleFileExtensions: [
    'js',
    'json',
    // tell Jest to handle `*.vue` files
    'vue',
  ],
  transform: {
    // process `*.vue` files with `vue-jest`
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest',
  },
  moduleNameMapper: {
    '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/mocks/fileMock.js',
    '\\.(css|less|scss)$': '<rootDir>/mocks/styleMock.js',
  },
  clearMocks: true,
};

1 个答案:

答案 0 :(得分:1)

问题是我必须更好地了解什么是嘲笑,并为此使用它们。

import { shallowMount, createLocalVue } from '@vue/test-utils';
import VueRouter from 'vue-router';
import Vuex from 'vuex';
import BootstrapVue from 'bootstrap-vue';
import UsersList from './../../components/users/UsersList.vue';

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

describe('UsersList.vue', () => {
  let store;
  const state = {
    User: {
      id: 1,
    },
  };

  beforeEach(() => {
    store = new Vuex.Store({
      state,
    });
  });

  it('renders a div', () => {
    const wrapper = shallowMount(UsersList, {
      store,
      localVue,
    });
    expect(wrapper.contains('div')).toBe(true);
  });
});

我给自己定义了一个嘲笑的状态,并且做到了魔术

const state = {
    User: {
      id: 1,
    },
  };