我很难在VueJS应用程序中进行简单的单元测试 .
我基本上试图测试模板并检查它是否包含一个类名为"version"的div元素,但测试仍然失败并出现 undefined is not a constructor (evaluating 'expect(component.$el.querySelector('div')).to.have.className('version')').
错误 .
这是一个简单的组件,以此为模板:
<template>
<div>
<div class="version">
<label>Version {{ version }}</label>
</div>
<div class="activityBanner">
<label>{{ user }}</label>
<router-link id="logout" :to="{name: 'logout' }">
<label>Logout</label>
</router-link>
</div>
</div>
</template>
这是我正在使用的单元测试:
import Vue from 'vue';
import router from '@/router';
import VueRouter from 'vue-router';
import Navigation from '@/components/Navigation';
describe('Navigation.vue', () => {
// Nice little helper to return our component within a div
const getComponent = data => {
const Constructor = Vue.extend(Navigation);
return new Constructor({
router
}).$mount();
};
describe('Component', () => {
it('should have a property "name"', () => expect(Navigation.name).to.be.a('string'));
it('should have a property "name" set to "Navigation"', () => expect(Navigation.name).to.equal('Navigation'));
it('should have a data hook', () => expect(Navigation.data).to.be.a('function'));
it('should have a default "currentView" set to "profileTable"', () => {
const defaultData = Navigation.data();
expect(defaultData.currentView).to.equal('profileTable');
});
it('should have a default "version" set to "0.5"', () => {
const defaultData = Navigation.data();
expect(defaultData.version).to.equal(0.5);
});
it('should have a default "user" set to "Bob Barker"', () => {
const defaultData = Navigation.data();
expect(defaultData.user).to.equal('Bob Barker');
});
});
describe('Template', () => {
Vue.use(VueRouter);
it('should render correctly', () => {
const component = getComponent();
expect(component.$el);
});
it('should have a "div" element', () => {
const component = getComponent();
expect(component.$el.querySelectorAll('div').length);
});
it('should have a element with a "className" set to "version"', () => {
const component = getComponent();
expect(component.$el.querySelector('div')).to.have.className('version');
});
});
});
我做错了什么?
1 回答
检查Vue测试工具:
Vue Test Utils
它使测试模板的工作变得非常轻松 .
这是一个例子: