组件单元测试 可以阅读Vue Test Utils
vue组件单元测试,就是测试组件里面的props的属性,测试一个属性,先赋值,然后写一个预期的结果。
下面是vue3 代码示例: 就是需要测试type、dark、 light 、closable,
<template>
<div class='tag'>
<div :class="[
'tag-size',
TagState
]">
<span v-if="closable" class="tag-close">×</span>
</div>
</div>
</template>
<script lang="ts">
export default {
name: 'Tag'
}
</script>
<script setup lang="ts">
import { computed } from 'vue'
export interface PropsInterface {
type?: string
dark?: boolean
closable?: boolean
}
const props = withDefaults(defineProps<PropsInterface>(), {
type: 'main',
dark: false,
closable: false
})
const TagState = computed(() => {
if (props.dark) {
return props.type ? 'tag-dark-' + props.type : 'tag-dark-main'
} else if (props.light) {
return props.type ? 'tag-light-' + props.type : 'tag-light-main'
}
return props.type ? 'tag-' + props.type : 'tag-main'
})
</script>
测试的代码如下:
expect(type.find('.tag-info').exists()).toBe(true) 表示一个预期的结果,find('.tag-info') 表示寻找tag-info的类,exists()存在,toBe(true)预期结果表示有。预期结果可以通过产看官网去了解有那些测试的类型。
import Tag from '@/components/main.vue'
import { mount } from '@vue/test-utils'
describe('tag', () => {
test('optional value', async () => {
const type = mount(Tag, {
props: {
type: 'info'
}
})
expect(type.find('.tag-info').exists()).toBe(true)
})
test('dark', async () => {
const wrapper = mount(Tag, {
props: {
dark: true,
type: 'info'
}
})
expect(wrapper.find('.tag-dark-info').exists()).toBe(true)
})
test('closable', async () => {
const wrapper = mount(Tag, {
props: {
closable: true
}
})
expect(wrapper.find('.tag-close').exists()).toBe(true)
})
})