You may be familiar with how to read data defined on your Vue components with the options API from within your unit tests. That looks like this:
wrapper.vm.$data
But most people these days prefer using the composition API along with script setup. Reading reactive data defined with ref and reactive during testing looks a little different. So how do you manage it?
⚠️ NOTE: that most unit tests should NOT need to read the components internal data directly. Instead you should prefer to read the rendered HTML output to ensure it’s displayed as expected.
Let’s say we have a component that looks like this. It has a reactive ref msg
defined. In the template we’ve bound the msg
data to an input with v-model
.
<!-- MyComponent.vue -->
<script setup>
import { ref } from "vue";
const msg = ref("");
</script>
<template>
<div id="my-id" class="my-class another-class">
<input type="text" v-model="msg" />
</div>
</template>
The data we define within script setup will be added as a property directly on the component instance. Therefore we can read from within our tests like this:
wrapper.vm.msg
So if we simulate the user typing in the input with setValue
then we can expect the msg
data to be updated.
const wrapper = mount(MyComponent);
// to start it's an empty string
expect(wrapper.vm.msg).toBe("");
// simulate user input
const input = wrapper.find("input");
await input.setValue("hello");
// now the msg data is equal to what the user typed
expect(wrapper.vm.msg).toBe("hello");
So there you have it! In limited situations where you might need to read a component’s reactive data from within your unit tests, now you know how! Remember though, checking component internal data should not be the approach you take most times. Instead, you should cultivate the habit of checking a component's rendered output.
Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.
More than 200.000 users have already joined us. You are welcome too!
© All rights reserved. Made with ❤️ by BitterBrains, Inc.