?閱讀前應(yīng)該具備:
了解vue相關(guān)知識(shí)
熟悉測(cè)試APP的UI
按照慣例,在Vue的生態(tài)中,當(dāng)您要測(cè)試應(yīng)用程序時(shí),您可以使用@ vue/test-utils-Vue的官方測(cè)試庫(kù)。這個(gè)庫(kù)提供相關(guān)API以方便用戶測(cè)試渲染的Vue組件實(shí)例。例如:
// example.spec.js
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = shallowMount(HelloWorld, {
propsData: { msg }
})
expect(wrapper.text()).toMatch(msg)
})
})
您可以看到我們正在使用@vue/test-utils庫(kù)提供的shallowMount函數(shù)來(lái)載入渲染我們項(xiàng)目開發(fā)代碼中Vue組件。
上述測(cè)試Vue組件的方法的問(wèn)題在于,用戶最終要與DOM進(jìn)行交互,對(duì)于Vue如何渲染UI沒(méi)有任何了解。相反,一般只會(huì)通過(guò)文本內(nèi)容、輸入框的標(biāo)簽以及頁(yè)面上的一些其他可見的視覺(jué)線索來(lái)尋找對(duì)應(yīng)UI元素是否可見。
一個(gè)更好的方法是為你的Vue應(yīng)用程序編寫測(cè)試用例,以反映實(shí)際用戶如何與之交互,例如在結(jié)賬頁(yè)面中尋找一個(gè)增加產(chǎn)品購(gòu)買數(shù)量的按鈕,所以才需要Vue測(cè)試庫(kù)。
Vue測(cè)試庫(kù)是什么?
Vue測(cè)試庫(kù)是Vue的一個(gè)輕量級(jí)測(cè)試庫(kù),它在@vue/test-utils的基礎(chǔ)上提供了輕量級(jí)的實(shí)用功能。它是根據(jù)一個(gè)簡(jiǎn)單的引導(dǎo)原則創(chuàng)建的:
The more your tests resemble the way your software is used, the more confidence they can give you.
— testing-library.com
為什么使用Vue測(cè)試庫(kù)?
- 你要寫的測(cè)試用例不需要關(guān)注于實(shí)現(xiàn)細(xì)節(jié),即測(cè)試方法的實(shí)現(xiàn)方式,而不是它是否產(chǎn)生了所需要的結(jié)果。
- 您想編寫針對(duì)實(shí)際DOM節(jié)點(diǎn)而不是渲染的Vue組件的測(cè)試。
- 您想要編寫以與用戶相同的方式查詢DOM的測(cè)試。
Vue測(cè)試庫(kù)的原理
Vue測(cè)試庫(kù)通過(guò)提供用于查詢DOM的功能來(lái)發(fā)揮作用,就像用戶與DOM進(jìn)行交互的方式一樣。這些實(shí)用的功能使您可以通過(guò)標(biāo)簽文本查找元素,從其文本內(nèi)容中找到鏈接和按鈕,并斷言可以完全訪問(wèn)Vue應(yīng)用程序。對(duì)于無(wú)法通過(guò)文字內(nèi)容或標(biāo)簽來(lái)查找元素或其它不切實(shí)際的情況,Vue測(cè)試庫(kù)提供了一種比較推薦的方法,即通過(guò)使用data-testid屬性作為標(biāo)記來(lái)查找這些元素。
data- testd屬性被添加到您計(jì)劃在測(cè)試中查詢的HTML元素中。如
<button data-testid="checkoutButton">Check Out</button>
開始使用Vue測(cè)試庫(kù)
現(xiàn)在,你已經(jīng)了解了為什么應(yīng)該使用Vue測(cè)試庫(kù)以及其工作方式,讓我們?cè)谌碌腣ue CLI創(chuàng)建的Vue項(xiàng)目中進(jìn)行配置。
首先,我們將通過(guò)在終端中運(yùn)行下面的命令創(chuàng)建一個(gè)新項(xiàng)目(假設(shè)您的機(jī)器上安裝了Vue CLI)
vue create vue-testing-library-demo
為了運(yùn)行測(cè)試,我們將使用Jest,它是Facebook開發(fā)的測(cè)試運(yùn)行程序。Vue CLI具有一個(gè)可以輕松配置Jest的插件。讓我們添加該插件:
添加完成后,您會(huì)發(fā)現(xiàn)在package.json中添加了一個(gè)新腳本:
"test:unit": "vue-cli-service test:unit",
這個(gè)腳本就是用來(lái)運(yùn)行測(cè)試用例的。它還在src中添加了一個(gè)新的tests文件夾,并在tests文件夾中添加了一個(gè)單元文件夾,其中包含一個(gè)名為example.spec.js的示例測(cè)試文件?;贘est的配置,當(dāng)我們運(yùn)行npm run test:unit時(shí),Jest將在tests目錄中查找文件并運(yùn)行測(cè)試文件。讓我們運(yùn)行示例測(cè)試文件:
這應(yīng)該會(huì)運(yùn)行test/unit目錄下的example.spec.js測(cè)試文件。讓我們看看這個(gè)文件的內(nèi)容。
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = shallowMount(HelloWorld, {
propsData: { msg }
})
expect(wrapper.text()).toMatch(msg)
})
})
默認(rèn)情況下,使用Vue CLI插件安裝Jest會(huì)安裝@vue/test-utils,因此上面的測(cè)試文件使用的是@vue/test-utils中的showMount函數(shù)。但是我們要使用Vue測(cè)試庫(kù)而不是@vue/test-utils。為此,我們將卸載@vue/test-utils,因?yàn)槲覀儗⒉恍枰?/p>
npm uninstall @vue/test-utils --save-dev
然后,我們安裝Vue測(cè)試庫(kù)
npm install @testing-library/vue --save-dev
接著,我們將tests/unit/example.spec.js修改為:
import { render } from '@testing-library/vue'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const { getByText } = render(HelloWorld, {
props: { msg }
})
getByText(msg)
})
})
再次運(yùn)行測(cè)試,應(yīng)該可以通過(guò)。讓我們看看我們做了什么:
- 我們使用Vue Testing Library公開的render函數(shù)來(lái)渲染HelloWorld組件。render是渲染Vue組件的唯一方法。調(diào)用render時(shí),需要傳入Vue組件和一個(gè)可選的options對(duì)象。
- 然后,我們使用options對(duì)象傳遞HelloWorld組件所需的參數(shù)。render將返回一個(gè)帶有輔助方法的對(duì)象來(lái)查詢DOM,而這些方法之一就是getByText。
- 最后,我們使用getByText斷言DOM中是否存在具有“新消息”文本內(nèi)容的元素。
到目前為止,您可能已經(jīng)注意到從考慮測(cè)試渲染的Vue組件到用戶在DOM中看到的轉(zhuǎn)變。這一轉(zhuǎn)變將使您從用戶的角度測(cè)試應(yīng)用程序,而不是將重點(diǎn)放在實(shí)現(xiàn)細(xì)節(jié)上。
我們的演示應(yīng)用
現(xiàn)在,我們已經(jīng)確定了如何使用Vue測(cè)試庫(kù)在Vue中完成測(cè)試,我們將繼續(xù)測(cè)試演示應(yīng)用程序。但是首先,我們將充實(shí)應(yīng)用程序的UI。我們的演示應(yīng)用程序是一個(gè)產(chǎn)品的簡(jiǎn)單結(jié)帳頁(yè)面。我們將測(cè)試用戶是否可以在結(jié)帳前增加產(chǎn)品的數(shù)量,他/她是否可以看到產(chǎn)品名稱和價(jià)格,等等。讓我們開始吧。
首先,在components /目錄中創(chuàng)建一個(gè)名為checkout的新Vue組件,并將以下代碼段添加到其中:
<template>
<div class="checkout">
<h1>{{ product.name }} - <span data-testid="finalPrice">${{ product.price }}</span></h1>
<div class="quantity-wrapper">
<div>
<label for="quanity">Quantity</label>
<input type="number" v-model="quantity" name="quantity" class="quantity-input" />
</div>
<div>
<button @click="incrementQuantity" class="quantity-btn">+</button>
<button @click="decrementQuantity" class="quantity-btn">-</button>
</div>
</div>
<p>final price - $<span data-testId="finalPrice">{{ finalPrice }}</span></p>
<button @click="checkout" class="checkout-btn">Checkout</button>
</div>
</template>
<script>
export default {
data() {
return {
quantity: 1,
}
},
props: {
product: {
required: true
}
},
computed: {
finalPrice() {
return this.product.price * this.quantity
}
},
methods: {
incrementQuantity() {
this.quantity++;
},
decrementQuantity() {
if (this.quantity == 1) return;
this.quantity--;
},
checkout() {
}
}
}
</script>
<style scoped>
.quantity-wrapper {
margin: 2em auto;
width: 50%;
display: flex;
justify-content: center;
}
.quantity-wrapper div {
margin-right: 2em;
}
.quantity-input {
margin-left: 0.5em;
}
.quantity-wrapper button {
margin-right: 1em;
}
button {
cursor: pointer;
}
</style>
再將App.vue改成:
<template>
<div id="app">
<check-out :product="product" />
</div>
</template>
<script>
import CheckOut from './components/CheckOut.vue'
export default {
name: 'App',
data() {
return {
product: {
name: 'Shure Mic SM7B',
price: 200,
}
}
},
components: {
CheckOut
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
對(duì)于我們的測(cè)試用例,我們將測(cè)試以下場(chǎng)景:
- 用戶可以看到產(chǎn)品名稱嗎?
- 用戶能看到產(chǎn)品價(jià)格嗎?
- 用戶能否增加產(chǎn)品數(shù)量?
- 用戶可以減少產(chǎn)品數(shù)量嗎?
- 用戶可以隨著數(shù)量的變化實(shí)時(shí)查看更新的總價(jià)嗎?
我們的UI界面是非常簡(jiǎn)約,因?yàn)橹攸c(diǎn)在于如何使用Vue測(cè)試庫(kù)進(jìn)行測(cè)試。讓我們繼續(xù)測(cè)試Checkout組件。在tests / unit /中創(chuàng)建一個(gè)名為checkout.spec.js的新測(cè)試文件內(nèi)容如下:
import { render, fireEvent } from '@testing-library/vue'
import CheckOut from '@/components/CheckOut.vue'
const product = {
name: 'Korg Kronos',
price: 1200
}
describe('Checkout.vue', () => {
// tests goes here
})
我們的第一個(gè)測(cè)試用例將是檢查產(chǎn)品名稱是否正常顯示。我們將這樣做:
it('renders product name', () => {
const { getByText } = render(CheckOut, {
props: { product }
})
getByText(product.name)
})
然后,我們將檢查產(chǎn)品價(jià)格是否正常顯示:
it('renders product price', () => {
const { getByText } = render(CheckOut, {
props: { product }
})
getByText("$" + product.price)
})
繼續(xù)測(cè)試Checkout組件,我們將使用getByDisplayValue helper方法測(cè)試用戶看到的初始數(shù)量是否為1:
it('renders initial quantity as 1', () => {
const { getByDisplayValue, getByText } = render(CheckOut, {
props: { product }
})
getByDisplayValue(1)
})
接下來(lái),我們將檢查當(dāng)用戶點(diǎn)擊增加產(chǎn)品數(shù)量的按鈕時(shí),是否增加了產(chǎn)品數(shù)量。為此,我們將使用Vue測(cè)試庫(kù)中的fireEvent實(shí)用程序觸發(fā)單擊事件。下面是完整的實(shí)現(xiàn)
it('increments product quantity', async () => {
const { getByDisplayValue, getByText } = render(CheckOut, {
props: { product }
})
const incrementQuantityButton = getByText('+')
await fireEvent.click(incrementQuantityButton)
getByDisplayValue(2)
})
當(dāng)數(shù)量為1時(shí),我們將做同樣的遞減操作-在這種情況下,我們不減少數(shù)量。
當(dāng)數(shù)量為2時(shí),讓我們編寫兩個(gè)測(cè)試用例。
it('does not decrement quantity when quanty is 1', async () => {
const { getByDisplayValue, getByText } = render(CheckOut, {
props: { product }
})
const decrementQuantityButton = getByText('-')
await fireEvent.click(decrementQuantityButton)
getByDisplayValue(1)
})
it('decrement quantity when quantity greater than 1', async () => {
const { getByDisplayValue, getByText } = render(CheckOut, {
props: { product }
})
const incrementQuantityButton = getByText('+')
const decrementQuantityButton = getByText('-')
await fireEvent.click(incrementQuantityButton)
await fireEvent.click(decrementQuantityButton)
getByDisplayValue(1)
})
最后,我們將測(cè)試是否可以點(diǎn)擊數(shù)量增減來(lái)查看最終價(jià)格是否正常顯示給用戶。
在整個(gè)測(cè)試案例中,您會(huì)注意到,我們更加專注于從用戶肉眼能看到并與之交互的角度編寫測(cè)試。以這種方式編寫測(cè)試可以確保我們測(cè)試的是對(duì)應(yīng)用的用戶比較重要的東西。
總結(jié)
本文介紹的于測(cè)試Vue應(yīng)用程序的庫(kù)和方法,稱為Vue測(cè)試庫(kù),我們將了解如何設(shè)置它以及如何使用它編寫Vue組件的測(cè)試用例。
您可以在GitHub上找到演示項(xiàng)目 https://github.com/DominusKelvin/vue-testing-library-demo
*原文鏈接: https://www.smashingmagazine.com/2020/11/vue-applications-vue-testing-library/