Currently, I am facing some challenges with testing a Vue component. The code below functions correctly, but when it comes to testing, I encounter issues. After conducting some research, I discovered that Vue 2.0 only uses the runtime-only build when importing Vue, and in order to resolve this, I either need to utilize vue/esm or employ the render function. However, my dilemma lies in the fact that I am not utilizing webpack or any build system (using tsconfig) to create an alias.
I attempted using template:'', but it still throws errors. When I tried using the render/createElement function, I found difficulty incorporating my own HTML file/template as it appears to only aim at creating a new element rather than injecting a template.
ERROR: '[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
COMPONENT:
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);
UNIT TEST:
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;
});
});
});