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