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
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With