【发布时间】:2020-12-11 18:13:28
【问题描述】:
我正在关注 Pluralsight 上的指南,开始学习如何在 Vue 和 Jest 中进行单元测试。我对 Vue 和 Jest 都很陌生。但这些测试非常简单明了,当它们显然没有通过时应该会通过。
这是我需要测试的 HiChild 组件。它有一个 message 属性和一个 error 变量,当 message 属性长于或小于 3 时会发生变化。
<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: "",
},
},
computed: {
error() {
return this.message.trim().length < 3
? " The child can say bigger words than that!"
: "";
},
},
};
这是我正在测试 HiChild 组件的单元测试。第一个测试尝试查看消息是否正确插入到组件中。第二个测试检查组件中的错误变量是否在给组件一个长于 3 的字符串和一个短于 3 的字符串时发生变化。
import { shallowMount } from '@vue/test-utils';
import HiChild from '@/components/HiChild.vue';
describe('HiChild.vue', () => {
it('renders props.msg when passed', () => {
const message = 'hello there!';
const wrapper = shallowMount(HiChild, {
propsData: { message },
});
expect(wrapper.text()).toMatch(message);
});
});
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);
});
});
这是两个测试的输出:
【问题讨论】:
标签: javascript vue.js jestjs