Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Vuejs and TypeScript with Jest causes an error "Property 'xxx' does not exist on type 'CombinedVueInstance'

I'm trying to create a basic test for a function in Vue component and failing miserably.

main.ts

new Vue({
  render: (h) => h(App),
  router,
  store,
}).$mount('#app')

App.ts

const App = Vue.extend({
    components: { MainContainer },
    data() {
        return {
            msg: 'Test',
        }
    },
    name: 'App',
    template: `<MainContainer />`,
})

export default App

MainContainer.vue

const MainContainer = Vue.extend({
    components: {
        Content,
    },
    methods: {
        sum: (a: number, b: number): number => a + b,
    },
})

export default MainContainer

MainContainer.spec.ts

import { createLocalVue, shallowMount } from '@vue/test-utils'

describe('MainComponent.vue', () => {
    const localVue = createLocalVue()

    test('sum method should add number together', () => {
    const wrapper = shallowMount(MainContainer, { localVue })
    expect(wrapper.vm.sum(1, 2)).toEqual(3)
})

Tests fails with the error

Property 'sum' does not exist on type 'CombinedVueInstance<Vue, object, object, object, Record<never, any>>'.

The same behavior I see if I try to test data.msg from App.ts. I'd appreciate any help. Thanks

like image 480
Anastasia Avatar asked Jan 18 '19 15:01

Anastasia


People also ask

Should you use TypeScript with Vue?

Another benefit or working with TypeScript for your Vue. js projects, is that you can refactor with more confidence. Let's say you had a PostForm component for a blog application that looked something like this in plain JavaScript. It keeps track of a title and a body as reactive references.

What is VUE extend?

Since Vue itself is a constructor, Vue. extend() is a class inheritance method. Its task is to create a sub-class of Vue and return the constructor. Vue. component() , on the other hand, is an asset registration method similar to Vue.


1 Answers

You must specify type of wrapper.vm

A solution that works is to specify type to any :

expect((wrapper.vm as any).sum(1, 2)).toEqual(3)
like image 155
Renan Bronchart Avatar answered Sep 16 '22 16:09

Renan Bronchart