0

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');
    });
})
skyboyer
  • 22,209
  • 7
  • 57
  • 64
PeiHua Li
  • 41
  • 1
  • 10
  • I can't see `HelloWorld` get declared anywhere in your test file. You are importing HelloWorld as `html` but you are trying to mount `HelloWorld` ? – Satyam Pathak Mar 20 '20 at 06:58
  • I am not familiar with vue.js. I want to make HelloWorld as a vue component in my test file to mount it. I have another practice project use .vue as template, they works well in same way, so I'm confuse about the related adoption about HTML string. – PeiHua Li Mar 20 '20 at 07:32
  • Can you give me some clues about this problem? Thank you. – PeiHua Li Mar 20 '20 at 07:37
  • Refer https://vue-test-utils.vuejs.org/guides/using-with-typescript.html – Satyam Pathak Mar 20 '20 at 07:47

0 Answers0