我想测试一个登录。有子BaseInput的value组件。vue组件。我尝试了下面的代码,也浅装,但我一直得到下面的错误。
TheLogin.vue
<template>
<section>
<legend>
Hello Login
</legend>
<BaseInput id="userName"></BaseInput>
</section>
</template>
export default {
name: 'TheLogin',
data() {
return {
userName: null
}
}
}
TheLogin.spec.js
import TheLogin from '@/pages/login/TheLogin.vue';
import BaseInput from '@/components/ui/BaseInput.vue';
import { createLocalVue, mount } from '@vue/test-utils';
describe('TheLogin.vue', () => {
const localVue = createLocalVue();
localVue.use(BaseInput); // no luck
it('renders the title', () => {
const wrapper = mount(TheLogin, {
localVue,
// stubs: {BaseInput: true // no luck either
// stubs: ['base-input'] // no luck again
});
expect(wrapper.find('legend').text()).toEqual(
'Hello Login'
);
});
我将基本组件导入到一个单独的文件中,并导入到main.js
import Vue from 'vue';
const components = {
BaseInput: () => import('@/components/ui/BaseInput.vue'),
BaseButton: () => import('@/components/ui/BaseButton.vue'),
//et cetera
};
Object.entries(components).forEach(([name, component]) =>
Vue.component(name, component)
);
得到的错误是:
TypeError: Cannot read property 'userName' of undefined
原来是vuvalidate导致错误(上面的代码不完整)。在我的脚本中还有:
validations: {
userName: {
required,
minLength: minLength(4)
},
password: {
required,
minLength: minLength(4)
}
}
我通过添加我的测试来解决它:
import Vuelidate from 'vuelidate';
import Vue from 'vue';
Vue.use(Vuelidate);
您是否尝试过在不使用localVue并将BaseInput
设置为存根的情况下浅层安装组件?
类似:
import TheLogin from '@/pages/login/TheLogin.vue';
import { shallowMount } from '@vue/test-utils';
describe('TheLogin.vue', () => {
it('renders the title', () => {
const wrapper = shallowMount(TheLogin, {
stubs: { BaseInput: true }
});
expect(wrapper.find('legend').text()).toEqual(
'Hello Login'
);
});
});