TypeScript support for Vue3 Composition components unit testing
Murat Sert
Posted on January 6, 2024
When testing Vue 3 Composition API-based components in TypeScript, you may encounter a TypeScript error while testing your components.
For example, let's consider a simple component that displays the value from an input field:
<script setup lang="ts">
import { ref } from 'vue';
const msg = ref('Hello World!');
</script>
<template>
<h1 id="msgDisplay">{{ msg }}</h1>
<input v-model="msg" id="msgInput" />
</template>
Suppose you want to write a unit test for this component:
it('Displays message correctly', async () => {
const wrapper = mount(DummyComponent, {});
const inputField = wrapper.find('#msgInput');
await inputField.setValue('test');
const msgDisplay = wrapper.find('#msgDisplay');
expect(msgDisplay.html()).toContain('test');
// TypeScript error
expect(wrapper.getComponent(DummyComponent).vm.msg).toBe('test');
});
During the test, you might encounter the TypeScript error: Vue: Property msg does not exist on type. To resolve this error, two small modifications are needed.
Firstly, expose the msg variable within the component:
defineExpose({
msg,
});
Finally, within the test, access the component using the wrapper.getComponent method:
expect(wrapper.getComponent(DummyComponent).vm.msg).toBe('test');
Voilà! 🚀 With these changes, the TypeScript error should be resolved.
Posted on January 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024