教你如何編寫(xiě)Vue.js的單元測(cè)試的方法
Vue.js是一個(gè)JavaScript框架,可用于構(gòu)建Web應(yīng)用程序的前端框架。特別是在創(chuàng)建復(fù)雜功能時(shí),對(duì)于每個(gè)項(xiàng)目,有必要在我們的應(yīng)用程序中查看所有內(nèi)容,并檢查它是否符合預(yù)期。然而,對(duì)于大型項(xiàng)目,每次新的更新后,檢查每個(gè)功能將變得很麻煩。因此,我們可以創(chuàng)建可以一直運(yùn)行的自動(dòng)化測(cè)試,并保證我們的代碼可以正常運(yùn)行。在本文中,我們將為VueJS創(chuàng)建一些簡(jiǎn)單的單元測(cè)試。
要進(jìn)行測(cè)試,我們將先制作一個(gè)基本的待辦事項(xiàng)列表組件。我們將測(cè)試該列表是否正確顯示,并且用戶(hù)可以將新項(xiàng)目添加到待辦事項(xiàng)列表中。希望在本教程結(jié)束之前,您可以編寫(xiě)測(cè)試,檢查您的組件輸出給用戶(hù),以及通過(guò)與HTML進(jìn)行交互來(lái)模擬用戶(hù)操作(例如通過(guò)單擊按鈕)。
本文中的所有代碼可以在 Github 下載。
搭建環(huán)境
搭建JavaScript項(xiàng)目可能是一個(gè)復(fù)雜的過(guò)程。有那么多庫(kù)需要選擇,所有這些庫(kù)的目的都略有不同。幸運(yùn)的是,對(duì)于VueJS,我們有vue-cli,它為我們?cè)O(shè)定了一切!您需要首先安裝npm,然后可以運(yùn)行以下命令:
npm install -g vue-cli vue init webpack project-name
在這個(gè)階段,你會(huì)被提示幾個(gè)問(wèn)題。大多數(shù)都可以直接繼續(xù),您可以選擇默認(rèn)選項(xiàng),唯一的要求是您回答YES以包括vue-router和YES來(lái)設(shè)置Karma和Mocha的單元測(cè)試。然后安裝依賴(lài)項(xiàng):
cd project-name npm install
這個(gè)最終命令將啟動(dòng)您的瀏覽器并打開(kāi)localhost運(yùn)行您的應(yīng)用程序:
npm run dev
下面是對(duì)vue-cli為我們?cè)O(shè)置的一些關(guān)鍵依賴(lài)關(guān)系(非常重要)的簡(jiǎn)要概述,包括為我自己的項(xiàng)目安裝的版本。
依賴(lài)
Webpack (v2.3) 是一個(gè)捆綁器,它結(jié)合了各種JavaScript,CSS,HTML(和其他)文件,使他們可以隨時(shí)由客戶(hù)端處理。
Babel (v6.22) 是ECMAScript 6到ECMAScript 5的編譯器。這些是不同的JavaScript標(biāo)準(zhǔn),目前的瀏覽器不能解析所有的ECMAScript 6,因此需要進(jìn)行轉(zhuǎn)換。
測(cè)試依賴(lài)關(guān)系
Karma (v1.4) 是一個(gè)測(cè)試運(yùn)行器,它運(yùn)行一個(gè)Web服務(wù)器,其中包含項(xiàng)目的應(yīng)用程序代碼,并對(duì)其執(zhí)行測(cè)試。
Mocha (v3.2) 是JavaScript的測(cè)試框架。
Chai (v3.5) 是可以與Mocha一起使用的斷言庫(kù)。
在您的項(xiàng)目中,您應(yīng)該能找到以下文件夾:build,config,node_modules,src,static和test。對(duì)本文來(lái)說(shuō),重要的是src,它將保存我們的應(yīng)用程序代碼并進(jìn)行test。
我的第一個(gè)測(cè)試
一個(gè)好的開(kāi)始需要去做一些基本工作。我們將從創(chuàng)建簡(jiǎn)單列表組件開(kāi)始。在src/components文件夾中創(chuàng)建一個(gè)名為L(zhǎng)ist.vue的新文件,并將以下代碼放在里面:
<template>
<div>
<h1>My To Do List</h1>
</br>
<!--displays list -->
<ul>
<li v-for="item in listItems">{{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'list',
data () {
return {
listItems: ['buy food', 'play games', 'sleep'],
}
}
}
</script>
在組件中,列表項(xiàng)存儲(chǔ)在組件數(shù)據(jù)中的數(shù)組(listItems)中。然后可以在模板中訪問(wèn)該數(shù)據(jù),并在foreach循環(huán)中循環(huán)(v-for),并顯示在頁(yè)面上。
為了使我們的列表看起來(lái)更有趣,我們可以創(chuàng)建一個(gè)新的路徑來(lái)顯示我們的組件。進(jìn)入src/router/index.js并添加路由,你的代碼應(yīng)該是這樣的:
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import List from '@/components/List'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
},
{
path: '/to-do',
name: 'ToDo',
component: List
},
]
})
現(xiàn)在,如果您導(dǎo)航到localhost:8080/#/to-do,您將在瀏覽器中看到您的列表效果!
首先我們要測(cè)試數(shù)據(jù)是否正確顯示。在 test/unit/specs 下創(chuàng)建一個(gè)新的文件List.spec.js并放上如下代碼:
import List from '@/components/List';
import Vue from 'vue';
describe('List.vue', () => {
it('displays items from the list', () => {
// our test goes here
})
})
在這個(gè)文件中,我們描述List.vue組件,我們有一個(gè)單獨(dú)的空測(cè)試,它將檢查它(組件)是否從列表中顯示項(xiàng)目。這是Mocha測(cè)試的基本文件結(jié)構(gòu)。
在我們的測(cè)試中,我們首先需要設(shè)置Vue組件。復(fù)制下面的代碼,并將其放在注釋“our test goes here”的位置:
// build component const Constructor = Vue.extend(List); const ListComponent = new Constructor().$mount();
我們擴(kuò)展Vue然后安裝我們的組件。安裝組件很重要,因?yàn)檫@是在我們的模板中呈現(xiàn)HTML。這實(shí)際上意味著HTML被構(gòu)建,并且我們的模板中的變量(例如{{item}})被填滿數(shù)據(jù),使得我們可以訪問(wèn)HTML(通過(guò)$el)。
隨著我們的組件準(zhǔn)備好,我們可以寫(xiě)第一個(gè)斷言。在這個(gè)例子中,我們使用了'expect'風(fēng)格,由Chai斷言庫(kù)提供,以及'should'和'assert'。 安裝組件后放置以下代碼:
// assert that component text contains items from the list
expect(ListComponent.$el.textContent).to.contain('play games');
如上所述,我們可以使用ListComponent.$el獲取組件的HTML,并且使用ListComponent.$el.textContent只訪問(wèn)內(nèi)部HTML(即文本)。斷言是檢查文本是否包含在組件數(shù)據(jù)中設(shè)置的列表項(xiàng)之一。
為了檢查一切都能正常工作,我們可以運(yùn)行測(cè)試!使用vue-cli項(xiàng)目,我們可以簡(jiǎn)單地輸入npm run unit,這是一個(gè)別名 cross-env BABEL_ENV = test karma start test/unit/karma.conf.js --single-run。
npm run unit
如果所有的測(cè)試都已經(jīng)通過(guò),它將顯示綠色,并顯示成功測(cè)試和代碼覆蓋率報(bào)告的列表,讓您知道在測(cè)試期間執(zhí)行的應(yīng)用程序代碼的百分比。
模擬用戶(hù)輸入
這是一個(gè)很好的開(kāi)始,但是很少有應(yīng)用程序只會(huì)顯示數(shù)據(jù)。我們要添加的下一個(gè)功能是讓用戶(hù)能夠在其列表中添加新項(xiàng)目。為此,我們需要一個(gè)輸入框,用戶(hù)可以在其中鍵入新項(xiàng)目,并在按鈕上添加項(xiàng)目到列表中。這是List.vue的更新版本:
<template>
<div>
<h1>My To Do List</h1>
</br>
<input v-model="newItem" >
<button @click="addItemToList">Add</button>
<!-- displays list -->
<ul>
<li v-for="item in listItems">{{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'test',
data () {
return {
listItems: ['buy food', 'play games', 'sleep'],
newItem: ''
}
},
methods: {
addItemToList() {
this.listItems.push(this.newItem);
this.newItem = '';
}
}
}
</script>
使用v-model,輸入框的值綁定到存儲(chǔ)在組件數(shù)據(jù)中的newItem變量。當(dāng)單擊按鈕時(shí),將執(zhí)行addItemToList函數(shù),將newItem添加到列表數(shù)組中,并清除newItem,以便可以將更多的內(nèi)容添加到列表中。
要開(kāi)始測(cè)試此功能,請(qǐng)?jiān)贚ist.spec.js中創(chuàng)建一個(gè)新的空測(cè)試,并添加測(cè)試代碼:
it('adds a new item to list on click', () => {
// our test goes here
})
首先我們要構(gòu)建我們的組件,并模擬一個(gè)用戶(hù)在輸入框中輸入的內(nèi)容。由于VueJS將輸入框的值綁定到newItem變量,所以我們可以簡(jiǎn)單地將我們的值設(shè)置為newItem。
// build component const Constructor = Vue.extend(List); const ListComponent = new Constructor().$mount(); // set value of new item ListComponent.newItem = 'brush my teeth';
接下來(lái)我們需要點(diǎn)擊按鈕。我們必須在HTML中找到這個(gè)按鈕,它可以使用$el。只有這一次,我們才可以使用querySelector來(lái)查找實(shí)際的元素。可以使用它的類(lèi)(.buttonClass),其id(#buttonId)或元素的名稱(chēng)(button)來(lái)找到一個(gè)元素。
// find button
const button = ListComponent.$el.querySelector('button');
為了模擬一個(gè)點(diǎn)擊,我們需要將按鈕傳遞給一個(gè)新的事件對(duì)象。在測(cè)試環(huán)境中,List組件不會(huì)監(jiān)聽(tīng)任何事件,因此我們需要手動(dòng)運(yùn)行監(jiān)視器。
// simulate click event
const clickEvent = new window.Event('click');
button.dispatchEvent(clickEvent);
ListComponent._watcher.run();
最后,我們需要檢查newItem是否顯示,我們已經(jīng)知道如何從第一個(gè)測(cè)試中完成!我們可能還想檢查newItem是否存儲(chǔ)在列表數(shù)組中。
//assert list contains new item
expect(ListComponent.$el.textContent).to.contain('brush my teeth');
expect(ListComponent.listItems).to.contain('brush my teeth');
以下是完整的測(cè)試文件:
import List from '@/components/List';
import Vue from 'vue';
describe('List.vue', () => {
it('displays items from the list', () => {
const Constructor = Vue.extend(List);
const ListComponent = new Constructor().$mount();
expect(ListComponent.$el.textContent).to.contain('play games');
})
it('adds a new item to list on click', () => {
// build component
const Constructor = Vue.extend(List);
const ListComponent = new Constructor().$mount();
// set input value
ListComponent.newItem = 'brush my teeth';
// simulate click event
const button = ListComponent.$el.querySelector('button');
const clickEvent = new window.Event('click');
button.dispatchEvent(clickEvent);
ListComponent._watcher.run();
// assert list contains new item
expect(ListComponent.$el.textContent).to.contain('brush my teeth');
expect(ListComponent.listItems).to.contain('brush my teeth');
})
})
現(xiàn)在我們可以再次運(yùn)行我們的測(cè)試,應(yīng)該會(huì)顯示綠色!
希望這段代碼對(duì)你來(lái)說(shuō)能夠很清楚,但是它不是特別容易理解,特別是對(duì)于第一次進(jìn)行VueJS測(cè)試的人來(lái)說(shuō)。有一個(gè)VueJS實(shí)用程序庫(kù),其中包含了一些更復(fù)雜的外觀代碼。要使用它,我們可以轉(zhuǎn)到我們的項(xiàng)目根目錄并運(yùn)行以下命令:
npm install avoriaz
現(xiàn)在我們可以隱藏mount()之后的Vue組件的設(shè)置,并且為了單擊按鈕,我們需要的是兩行代碼:find()該按鈕和dispatch() )點(diǎn)擊事件。
import { mount } from 'avoriaz';
import List from '@/components/List';
import Vue from 'vue';
describe('List.vue', () => {
// previous tests ..
it('adds new item to list on click with avoriaz', () => {
// build component
const ListComponent = mount(List);
// set input value
ListComponent.setData({
newItem: 'brush my teeth',
});
// simulate click event
const button = ListComponent.find('button')[0];
button.dispatch('click');
// assert list contains new item
expect(ListComponent.text()).to.contain('brush my teeth');
expect(ListComponent.data().listItems).to.contain('brush my teeth');
})
})
總結(jié)
我個(gè)人認(rèn)為寫(xiě)作測(cè)試對(duì)于我的正常工作流程至關(guān)重要,但是使用JavaScript,特別是VueJS,我開(kāi)始碰到一些麻煩。希望本教程將幫助任何與我一樣遇到麻煩的人!
本文中的所有代碼可以在 Github 下載。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- vue 單元測(cè)試初探
- 詳解關(guān)于Vue單元測(cè)試的幾個(gè)坑
- 淺談Vue組件單元測(cè)試究竟測(cè)試什么
- 使用Karma做vue組件單元測(cè)試的實(shí)現(xiàn)
- vue-cli3 karma單元測(cè)試的實(shí)現(xiàn)
- 如何為vue的項(xiàng)目添加單元測(cè)試
- 對(duì) Vue-Router 進(jìn)行單元測(cè)試的方法
- 詳解使用jest對(duì)vue項(xiàng)目進(jìn)行單元測(cè)試
- vue項(xiàng)目中添加單元測(cè)試的方法
- 詳解Vue單元測(cè)試case寫(xiě)法
- vue 單元測(cè)試的推薦插件和使用示例
相關(guān)文章
vue項(xiàng)目創(chuàng)建步驟及路由router
本文主要給大家分享了vue項(xiàng)目的創(chuàng)建步驟以及vue路由router的相關(guān)知識(shí)點(diǎn),非常的實(shí)用,有需要的小伙伴可以來(lái)參考下2020-01-01
Vue利用computed配合watch實(shí)現(xiàn)監(jiān)聽(tīng)多個(gè)屬性的變化
這篇文章主要給大家介紹了在Vue中巧用computed配合watch實(shí)現(xiàn)監(jiān)聽(tīng)多個(gè)屬性的變化的方法,文中有詳細(xì)的代碼示例供大家參考,具有一定的參考價(jià)值,需要的朋友可以參考下2023-10-10
Vue.js實(shí)現(xiàn)對(duì)視頻預(yù)覽的示例代碼
本文主要介紹了Vue.js實(shí)現(xiàn)對(duì)視頻預(yù)覽的示例代碼,通過(guò)監(jiān)聽(tīng)文件選擇事件和使用FileReader API,可以實(shí)現(xiàn)視頻文件的預(yù)覽功能,感興趣的可以了解一下2025-01-01

