單元測試,就是爲了測試某一個類或者是某一個方法能否正常工作而寫的測試代碼。
關於單元測試
是什麼:單元測試是針對 程序的最小單元 來進行正確性檢驗的測試工作。就是測試某一個頁面或者是某一個方法來進行測試的代碼單元。
意義:可以減少bug,提高代碼的效率質量,同時可以快速定位bug存在的地點位置,減少調試時間,放心重構代碼。
目的:當我們的項目足夠大的時候,在重疊的模塊和組件的過程中,可能會有影響到之前的模板。
測試命令:npm run unit
測試的文件內容(List.vue):
<template>
<div>
<h1>My To Do List</h1>
<br/>
<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>
測試的路由配置(index.js):
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import List from '@/components/List'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/to-do',
name: 'ToDo',
components: List
},
]
});
配置的測試文件內容(List.spc.js):
import Vue from 'vue';
import List from '@/components/List';
describe('List.vue', () => {
it('displays items from the list', () => {
// 獲取mount中的組件實例
const Constructor = Vue.extend(List);
const ListComponent = new Constructor().$mount();
// 測試是否錯誤代碼
// expect(vmComponent.count).toBe(2);
})
})