报错点:
1.Cannot read property ‘_t’ of undefined
2. Unknown custom element: - did you register the component correctly?

解决方法:直接看下面代码就好了

有不懂的加我微信号yizheng369


// 1导入:vue测试工具类
// import Vue from 'vue';
import {shallowMount, mount, createLocalVue } from '@vue/test-utils';
const localVue = createLocalVue();

// 2导入:element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

// 3导入:vuex
import store from '../../client/store/index.js';

// 4导入:mixin
import mixin from '../../client/views/js/mixin.js';
localVue.mixin(mixin);

// 5导入:要测试的组件
import Login from '../../client/views/layout/Login.vue';

/* --------中引文switch start----------------- */
import VueI18n from 'vue-i18n';
import enLocale from 'element-ui/lib/locale/lang/en';
import zhLocale from 'element-ui/lib/locale/lang/zh-CN';
import zhmsg from '../../public/lang/zh.json';
import enmsg from '../../public/lang/en.json';

localVue.use(VueI18n)

const messages = {
  en: {
    ...enmsg,
    ...enLocale
  },
  zh: {
    ...zhmsg,
    ...zhLocale
  }
};
// Create VueI18n instance with options 中引文switch
var i18n = new VueI18n({
  locale: 'zh',
  messages, // set locale messages
  silentTranslationWarn: true
});
window.Languages = i18n;

// 这里全部注册element:解决报错2
localVue.use(ElementUI, {
  i18n: function (path, options) {
    let value = i18n.t(path, options);
    if (value !== null && value !== undefined) return value;
    return '';
  }
});


// 6.更多匹配器请看官网 (jest官网 https://www.jestjs.cn/)

var wrapper = mount(Login, {
  localVue,
  store,
  propsData: {
    showLogin: showLoginPage
  },
  mocks: {
    $t: (a,b) => i18n.t(a,b), // 这里处理国际化:解决报错1
  },
});

// 测试套件
describe('Login-vue组件', () => {
    // 测试用例

  // 1.测试data上面的值
  test('测试data上面的值:', () => {
    expect(wrapper.vm.msg).toBe('login page12');
  });

  test('登录按钮:', () => {
    console.log('wrapper.vm.userInfo:',wrapper.vm.userInfo);
    let btnT =wrapper.find('#loginBtn').text()
    console.log('btnT-text:', btnT);
    expect(btnT).toBe('确定1');
  });

  // 2.调用组件的方法method
  test('调用组件的方法method:--登录方法', async() => {

    // 准备数据
    wrapper.vm.form = {
      username: 'admin',
      password: '123456'
    }
    wrapper.vm.sureLogin();
    console.log('this.userInfo.username', wrapper.vm.userInfo.username);
    expect(wrapper.vm.userInfo).toBeTruthy()
  });
  
  test('关闭按钮:', () => {
    let btnT =wrapper.find('#cancelBtn').text()
    console.log('btnT:', btnT);
    expect(btnT).toBe('关闭1');
  });
});

Logo

前往低代码交流专区

更多推荐