【发布时间】:2018-03-08 20:28:25
【问题描述】:
我目前在测试 vue 组件时遇到问题,下面的代码确实有效,但测试不起作用。我做了一些搜索,我知道 Vue 2.0 在导入 vue 时仅使用运行时构建并且我需要使用 vue/esm 或使用渲染功能时存在问题。我遇到的问题是我没有使用 webpack 或任何构建系统(使用 tsconfig)来创建别名。
我试过只使用模板:'',但仍然出错。当我使用 render/createElement 函数时,我似乎无法添加自己的 html 文件/模板,因为它似乎只想创建一个新元素而不是注入模板。
错误:'[Vue 警告]:您正在使用仅运行时构建的 Vue,其中模板编译器不可用。要么将模板预编译成渲染函数,要么使用编译器包含的构建。
组件:
import {
debounce
}
from 'npmPackage/debounce';
import Vue from 'vue';
import Component from 'vue-class-component';
import './navigation-bar.styles.less';
import {
menuItemList,
secondaryButton
}
from './types';
@ Component({
props: ['panels', 'secondaryButton'],
// render: (createElement) => { return createElement('div', require('./navigation-bar.html')); }
template: require('./navigation-bar.html')
})
export class NavigationBar extends Vue {
public menuActive: boolean = false;
public menuClass: string = '';
public panels: menuItemList;
public secondaryButton: secondaryButton;
private animateMenu: () => void = debounce(this.toggleMenuClass, 300, true);
public toggleMenu(): void {
this.animateMenu();
}
private toggleMenuClass(): void {
this.menuActive = !this.menuActive;
this.menuClass = this.menuActive ? 'show' : 'hide';
}
}
Vue.component('navigation-bar', NavigationBar);
单元测试:
import {
expect
}
from 'chai';
import {
spy,
stub
}
from 'sinon';
import Vue from 'vue';
import {
NavigationBar
}
from '../src/navigation-bar.component'
import {
IMenuItem
}
from "../src/types";
describe('Navigation bar component', () => {
let panels: Array < IMenuItem > ;
let navigationBar: NavigationBar;
beforeEach(() => {
panels = [{
label: 'my-account',
action: function () {}
}, {
label: 'home',
action: stub
}
];
navigationBar = new NavigationBar();
navigationBar.$mount();
});
describe('Checks that only one action is being called per panel', () => {
it('checks actions are called', () => {
console.log(navigationBar.$el);
navigationBar.panels = panels;
const menuItem = navigationBar.$el.querySelectorAll('.menu-item');
menuItem.length.should.equal(panels.length);
const menuItem1 = menuItem[0];
menuItem1.should.be.instanceOf(HTMLElement);
const html = menuItem1 as HTMLElement;
html.click();
panels[0].action.should.have.been.calledOnce;
panels[1].action.should.not.have.been.called;
});
});
});
【问题讨论】:
标签: javascript npm vue.js vuejs2 vue-component