I am a beginner of Vue.js, now I want to test my vue.js component by Jest.js, typescript, vue-class-component and vue-test-util. But I faced a challenge to mount separate vue component in my jest test script, because I use HTML string rather than default template(.vue).
I declared my html module in my .d.ts file to convert html into string.
declare module '*.html' {
const value: string;
export default value
}
And I separated typescript and HTML
HelloWorld.html
<div class="hello">
<h1>JEST UNIT TEST</h1>
<h2>{{ msg }}</h2>
<button @click="onClick">click me</button>
</div>
HelloWorld.ts
import html from './HelloWorld.html';
@VueComponent({
template: html
})
export class HelloWorld extends Vue {
msg = 123;
onClick () {
this.msg = 'new message'
}
}
and In my main.ts will create Vue instance
const appVM = new Vue({
name: 'app',
data: {
},
components: {
'hello-world': HelloWorld
},
router: router,
methods: {
}
});
$(function () {
appVM.$mount("#app");
});
Now I try to write my unit test to test component. I don't know how to mount my html file component by jest and vue-test-util. It showed "No overload match this call" in shallowmount function, because html string cannot be converted to vue component. Please help me, thanks in advance.
import { shallowMount } from '@vue/test-utils'
import html from '@/components/HelloWorld.html'
describe('HelloWorld', () => {
const wrapper = shallowMount(HelloWorld);
it('render msg when passed', () => {
const msg = '123'
expect(wrapper.find('h2').text()).toMatch(msg);
})
it("update 'msg' correctly",async() => {
await wrapper.find('button').trigger('click');
expect(wrapper.find('h2').text())
.toEqual('new message');
});
})