我在测试vue组件时遇到了问题,下面的代码实际上可以工作,但测试并不起作用。我做了一些搜索,我意识到在导入Vue时vue 2.0只使用运行时构建的问题,我需要使用vue/esm或使用render函数。我遇到的问题是,我没有使用webpack或任何构建系统(使用tsconfig)来创建别名。
我已经尝试使用模板:‘’,但它仍然出错。当我使用render/createElement函数时,我似乎不能添加到我自己的html文件/模板中,因为它似乎只想创建一个新元素,而不是注入一个模板。
错误:'Vue warn:您正在使用模板编译器不可用的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;
});
});
});
发布于 2017-09-27 11:16:40
获取Vue的CDN版本的副本并导入该版本,而不是npm Vue。
或者你也可以使用import Vue from vue/dist/vue.js
https://stackoverflow.com/questions/46446372
复制