?閱讀前應該具備:
了解vue相關(guān)知識
熟悉測試APP的UI
按照慣例,在Vue的生態(tài)中,當您要測試應用程序時,您可以使用@ vue/test-utils-Vue的官方測試庫。這個庫提供相關(guān)API以方便用戶測試渲染的Vue組件實例。例如:
// 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庫提供的shallowMount函數(shù)來載入渲染我們項目開發(fā)代碼中Vue組件。
上述測試Vue組件的方法的問題在于,用戶最終要與DOM進行交互,對于Vue如何渲染UI沒有任何了解。相反,一般只會通過文本內(nèi)容、輸入框的標簽以及頁面上的一些其他可見的視覺線索來尋找對應UI元素是否可見。
一個更好的方法是為你的Vue應用程序編寫測試用例,以反映實際用戶如何與之交互,例如在結(jié)賬頁面中尋找一個增加產(chǎn)品購買數(shù)量的按鈕,所以才需要Vue測試庫。
Vue測試庫是什么?
Vue測試庫是Vue的一個輕量級測試庫,它在@vue/test-utils的基礎(chǔ)上提供了輕量級的實用功能。它是根據(jù)一個簡單的引導原則創(chuàng)建的:
The more your tests resemble the way your software is used, the more confidence they can give you.
— testing-library.com
為什么使用Vue測試庫?
- 你要寫的測試用例不需要關(guān)注于實現(xiàn)細節(jié),即測試方法的實現(xiàn)方式,而不是它是否產(chǎn)生了所需要的結(jié)果。
- 您想編寫針對實際DOM節(jié)點而不是渲染的Vue組件的測試。
- 您想要編寫以與用戶相同的方式查詢DOM的測試。
Vue測試庫的原理
Vue測試庫通過提供用于查詢DOM的功能來發(fā)揮作用,就像用戶與DOM進行交互的方式一樣。這些實用的功能使您可以通過標簽文本查找元素,從其文本內(nèi)容中找到鏈接和按鈕,并斷言可以完全訪問Vue應用程序。對于無法通過文字內(nèi)容或標簽來查找元素或其它不切實際的情況,Vue測試庫提供了一種比較推薦的方法,即通過使用data-testid屬性作為標記來查找這些元素。
data- testd屬性被添加到您計劃在測試中查詢的HTML元素中。如
<button data-testid="checkoutButton">Check Out</button>
開始使用Vue測試庫
現(xiàn)在,你已經(jīng)了解了為什么應該使用Vue測試庫以及其工作方式,讓我們在全新的Vue CLI創(chuàng)建的Vue項目中進行配置。
首先,我們將通過在終端中運行下面的命令創(chuàng)建一個新項目(假設(shè)您的機器上安裝了Vue CLI)
vue create vue-testing-library-demo
為了運行測試,我們將使用Jest,它是Facebook開發(fā)的測試運行程序。Vue CLI具有一個可以輕松配置Jest的插件。讓我們添加該插件:
添加完成后,您會發(fā)現(xiàn)在package.json中添加了一個新腳本:
"test:unit": "vue-cli-service test:unit",
這個腳本就是用來運行測試用例的。它還在src中添加了一個新的tests文件夾,并在tests文件夾中添加了一個單元文件夾,其中包含一個名為example.spec.js的示例測試文件?;贘est的配置,當我們運行npm run test:unit時,Jest將在tests目錄中查找文件并運行測試文件。讓我們運行示例測試文件:
這應該會運行test/unit目錄下的example.spec.js測試文件。讓我們看看這個文件的內(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)
})
})默認情況下,使用Vue CLI插件安裝Jest會安裝@vue/test-utils,因此上面的測試文件使用的是@vue/test-utils中的showMount函數(shù)。但是我們要使用Vue測試庫而不是@vue/test-utils。為此,我們將卸載@vue/test-utils,因為我們將不需要它。
npm uninstall @vue/test-utils --save-dev
然后,我們安裝Vue測試庫
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)
})
})再次運行測試,應該可以通過。讓我們看看我們做了什么:
- 我們使用Vue Testing Library公開的render函數(shù)來渲染HelloWorld組件。render是渲染Vue組件的唯一方法。調(diào)用render時,需要傳入Vue組件和一個可選的options對象。
- 然后,我們使用options對象傳遞HelloWorld組件所需的參數(shù)。render將返回一個帶有輔助方法的對象來查詢DOM,而這些方法之一就是getByText。
- 最后,我們使用getByText斷言DOM中是否存在具有“新消息”文本內(nèi)容的元素。
到目前為止,您可能已經(jīng)注意到從考慮測試渲染的Vue組件到用戶在DOM中看到的轉(zhuǎn)變。這一轉(zhuǎn)變將使您從用戶的角度測試應用程序,而不是將重點放在實現(xiàn)細節(jié)上。
我們的演示應用
現(xiàn)在,我們已經(jīng)確定了如何使用Vue測試庫在Vue中完成測試,我們將繼續(xù)測試演示應用程序。但是首先,我們將充實應用程序的UI。我們的演示應用程序是一個產(chǎn)品的簡單結(jié)帳頁面。我們將測試用戶是否可以在結(jié)帳前增加產(chǎn)品的數(shù)量,他/她是否可以看到產(chǎn)品名稱和價格,等等。讓我們開始吧。
首先,在components /目錄中創(chuàng)建一個名為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>
對于我們的測試用例,我們將測試以下場景:
- 用戶可以看到產(chǎn)品名稱嗎?
- 用戶能看到產(chǎn)品價格嗎?
- 用戶能否增加產(chǎn)品數(shù)量?
- 用戶可以減少產(chǎn)品數(shù)量嗎?
- 用戶可以隨著數(shù)量的變化實時查看更新的總價嗎?
我們的UI界面是非常簡約,因為重點在于如何使用Vue測試庫進行測試。讓我們繼續(xù)測試Checkout組件。在tests / unit /中創(chuàng)建一個名為checkout.spec.js的新測試文件內(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
})我們的第一個測試用例將是檢查產(chǎn)品名稱是否正常顯示。我們將這樣做:
it('renders product name', () => {
const { getByText } = render(CheckOut, {
props: { product }
})
getByText(product.name)
})然后,我們將檢查產(chǎn)品價格是否正常顯示:
it('renders product price', () => {
const { getByText } = render(CheckOut, {
props: { product }
})
getByText("$" + product.price)
})繼續(xù)測試Checkout組件,我們將使用getByDisplayValue helper方法測試用戶看到的初始數(shù)量是否為1:
it('renders initial quantity as 1', () => {
const { getByDisplayValue, getByText } = render(CheckOut, {
props: { product }
})
getByDisplayValue(1)
})接下來,我們將檢查當用戶點擊增加產(chǎn)品數(shù)量的按鈕時,是否增加了產(chǎn)品數(shù)量。為此,我們將使用Vue測試庫中的fireEvent實用程序觸發(fā)單擊事件。下面是完整的實現(xiàn)
it('increments product quantity', async () => {
const { getByDisplayValue, getByText } = render(CheckOut, {
props: { product }
})
const incrementQuantityButton = getByText('+')
await fireEvent.click(incrementQuantityButton)
getByDisplayValue(2)
})當數(shù)量為1時,我們將做同樣的遞減操作-在這種情況下,我們不減少數(shù)量。
當數(shù)量為2時,讓我們編寫兩個測試用例。
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)
})最后,我們將測試是否可以點擊數(shù)量增減來查看最終價格是否正常顯示給用戶。
在整個測試案例中,您會注意到,我們更加專注于從用戶肉眼能看到并與之交互的角度編寫測試。以這種方式編寫測試可以確保我們測試的是對應用的用戶比較重要的東西。
總結(jié)
本文介紹的于測試Vue應用程序的庫和方法,稱為Vue測試庫,我們將了解如何設(shè)置它以及如何使用它編寫Vue組件的測試用例。
您可以在GitHub上找到演示項目 https://github.com/DominusKelvin/vue-testing-library-demo
*原文鏈接: https://www.smashingmagazine.com/2020/11/vue-applications-vue-testing-library/