vue 组件单元测试

组件单元测试 可以阅读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)
  })
})
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值