I have a small project where I am learning to write jest Unit tests in Vue. Inside this project I have a HiChild component which gets a message props. When the length of this message is smaller then 3 then a error div should show. I use v-if="error"
to check if the I should show the div or not.
This is the component:
<template>
<div>
<h2>The child says {{ message }}</h2>
<div class="error" v-if="error">{{ error }}</div>
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
default: "Hello",
},
},
computed: {
error() {
return this.message.trim().length < 3
? " The child can say bigger words than that!"
: "";
},
},
};
</script>
But in the unit test I wrote for this component I have a test where I test if the div actually exists when the error variable is not empty and not exist when it is empty. But the test does not pass when it should be empty. This is the unit test I wrote:
describe('HiChild.vue', () => {
it('renders error when message is too short', () => {
const wrapper = shallowMount(HiChild, {
propsData: { message: 'hi' },
});
expect(wrapper.find('.error').exists()).toBe(true);
wrapper.setProps({ message: 'good day to you!' });
expect(wrapper.find('.error').exists()).toBe(false);
});
});
And here is the output from the test:
Because:
computed: {
error() {
return this.message.trim().length < 3
? " The child can say bigger words than that!"
: "";
},
"" is different to false
"" !== false
return directly false like that
computed: {
error() {
return this.message.trim().length < 3
? " The child can say bigger words than that!"
: false;
},
Regards
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.