Vite Vue 單元測試attributes 判斷屬性

describe:是用來將一至多組有相關的測試組合在一起的區塊。

attributes:判斷屬性

attributes:判斷屬性。
classes:尋找 class 屬性,語法查詢的話將得到一個陣列的結果。。
target:尋找target 屬性。
mount:掛載。
data-test:在html綁定。
props:父傳子。
find():使用 Document.querySelector() 的語法,find() 沒有找到目標元素時不會拋出錯誤。
expect(value):攥寫每一筆測試時都會使用 expect(value) 和匹配器 (matcher) 來『斷言』某個值,expect (value) 的參數 value 會是程式碼產生的值
toContain('C'):包含

案例父傳子attributes判斷屬性 單元測試

defineProps

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//html
<template>
<a class="link A C B"
data-test="link"
:href="href" :target="target">點擊</a>
</template>

<script setup lang="ts">
const props = defineProps({
href: { type: String ,required: false },
target: { type: String, required: false },
})

</script>
單元測試
引入描述、它、斷言 =>引入測試mount程式 =>引入組件 =>定義 =>斷言
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//引入描述、它、斷言
import { describe, it, expect } from 'vitest'
//引入測試實用程式
import { mount } from '@vue/test-utils'
//引入元件
import AButton from '../A.vue'

describe('A標籤', () =>
{
const href = 'https://ithelp.ithome.com.tw/'
const target = '_blank'
// 定義 wrapper掛載AButton元件的父傳子資料
let wrapper
if (typeof document !== 'undefined') {
//掛載AButton元件,父傳子
wrapper = mount(AButton, {
props: {
href: href,
target: target
}
})
}

it('取得A標籤所有訊息,A標籤樣式是否包含link', () =>
{
if (typeof document !== 'undefined') {
//取得A標籤attributes所有訊息
wrapper.find('[data-test="link"]').attributes()
console.log('取得所有A標籤訊息', wrapper.find('[data-test="link"]').attributes())
//斷言A標籤class是否包含link
expect(wrapper.find('[data-test="link"]').classes()).toContain('link')
}
})

it('取得A標籤所有class訊息', () =>
{
if (typeof document !== 'undefined') {
//A標籤class是否包含link
expect(wrapper.find('[data-test="link"]').classes()).toContain('link')

//斷言A標籤class是否包含A
expect(wrapper.find('[data-test="link"]').classes()).toContain('A')

//斷言A標籤class是否包含C
expect(wrapper.find('[data-test="link"]').classes()).toContain('C')

//斷言A標籤class是否包含B
expect(wrapper.find('[data-test="link"]').classes()).toContain('B')

//斷言取得A標籤所有class訊息
console.log('取得A標籤所有class訊息', wrapper.find('[data-test="link"]').classes())
//[ 'link', 'A', 'C', 'B' ]
}
})
})

Vue 單元測試text()& html()內容物