vue學習—單元測試

參考1111

karma 單元測試

# 1, 初始化時,需要選擇打開test功能,然後選擇karma測試
vue init  webpack  testtodo 

# 2, 運行測試,test目錄會出現coverage--icov-report--index.html 
# 瀏覽器打開這個index.html,可以查看所有的測試地方
npm run unit

# 3, 安裝vue.js 官方的單元測試實用工具庫
npm  install  --save-dev    @vue/test-utils@1.0.0-beta.12

mocha 是個測試框架,本身不帶斷言層,所以需要引進Chai 斷言庫實現單元測試
在這裏插入圖片描述

筆記總結

  • Util.js 方法包含了大多數Vue組件化的測試需求。

  • vm.elvm.el vm.nextTick 和 vm.refVuevm.ref 都是在測試過程中比較常用的一些Vue語法糖。 需要注意: vm.nextTick 方法是異步的,所以需要在裏面使用done方法。

  • 異步斷言,方法參數需要是 _ 或者 done

  • 大多數時候查詢元素通過 querySelector 方法查詢class獲得
    vm.$el.querySelector(’.el-breadcrumb’).innerText

  • 大多數情況下查詢是否存在某個Class通過 classList.contains 方法獲得,查找的結果爲 true 或 false

vm.$el .classList.contains(‘el-button–primary’)

  • 異步測試必須以 done() 方法結尾。setTimeout 和 vm.$nextTick 是常用的異步測試。

由於 Vue 進行異步更新 DOM 的情況,一些依賴 DOM 更新結果的斷言必須在 vm.$nextTick() resolve 之後進行:

// 引用vue
import Vue from 'vue';
// 引用要測試的組件
import app from '../../src/app.vue';
// 描述要測試的內容
describe('test app.vue', () => {
    // 異步數據更新
    it('數據更新後,視圖應該改變', done => {
        // 這裏將app生成vue實例,並使用 $mount() 模擬掛載狀態
        let vm = new Vue(app).$mount();
        // 掛載後改變title
        vm.title = 'APP';
        Vue.nextTick(() => {
            let title = vm.$el.getElementsByTagName('h1')[0]
            expect(title.textContent).toEqual('APP')
            done();
        })
    });
});
describe 的鉤子(生命週期)
describe('hooks', function() {
  before(function() {
    // 在本區塊的所有測試用例之前執行
  });
  after(function() {
    // 在本區塊的所有測試用例之後執行
  });
  beforeEach(function() {
    // 在本區塊的每個測試用例之前執行
  });
  afterEach(function() {
    // 在本區塊的每個測試用例之後執行
  });
  // test cases
});

官方Demo的HelloWorld.spec.js代碼

import Vue from 'vue' // 導入Vue用於生成Vue實例
import Hello from '@/components/Hello' // 導入組件
// 測試腳本里面應該包括一個或多個describe塊,稱爲測試套件(test suite)
describe('Hello.vue', () => {
  // 每個describe塊應該包括一個或多個it塊,稱爲測試用例(test case)
  it('should render correct contents', () => {
    const Constructor = Vue.extend(Hello) // 獲得Hello組件實例
    const vm = new Constructor().$mount() // 將組件掛在到DOM上
    //斷言:DOM中class爲hello的元素中的h1元素的文本內容爲Welcome to Your Vue.js App
    expect(vm.$el.querySelector('.hello h1').textContent)
      .to.equal('Welcome to Your Vue.js App')  
  })
})

單元測試實例Demo代碼

學習vue單元測試–視頻

<template>
    <div>
        <section class="todoapp">
            <header class="header">
                <h1>todos</h1>
                <input  v-model="newtodo"  @keyup.enter="addtodo"  class="newtodo" autofocus autocomplete="off"
                placeholder="what needs to be done?" >
            </header>
            <section class="main" >
                <ul class="todo-list">
                    <li  v-for="todo in todos"   :key="todo.id"    class="todo"   >
                        <div class="view">
                            <label>{{todo.text}}</label>
                            <button  @click="deltodo(todo)"    class="destroy">刪除</button>
                        </div>
                        <input  v-model="todo.text"   class="edit"  type="text"/>
                    </li>
                </ul>
            </section>
        </section>
    </div>                        
</template>

<script>
export default {
  name: 'todoMVC',
  data () {
    return {
      todos:[
          {    id:Math.random(),  text:"CSS"   },
          {    id:Math.random(),  text:"html"  }
      ],
      newtodo:''
    }
  },
  methods:{
    addtodo:function(){
      this.todos.push(
        {
        id: Math.random(),   
        text:this.newtodo
       }
      )
      this.newtodo=''
    },
    deltodo:function(todo){
      let index = this.todos.indexOf(todo);
      this.todos.splice(index,1)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
html,body{
  margin: 0;
  padding: 0;
}
button {
  margin: 10px  30px;
  padding: 5px;
  border: 1px;
  background: rgb(126, 167, 126);
  font-size: 100%;
}
body{
  line-height: 1.4em;
}
</style>

在這裏插入圖片描述

todoMVC.spec.js 文件—測試用例

import {mount}  from '@vue/test-utils'
import todoMVC from '@/components/todoMVC'

// 創建測試套件
describe('HelloWorld.vue', () => {

  // 創建-- 查看 --測試用例
  it('測試查看功能', () => {
    // 通過mount 將組件渲染出來
    const wrapper = mount(todoMVC);
    // 尋找制定的dom元素
    console.log(wrapper.find('.todo-list'))   
    // 通過vm查看data中的某個數據
    console.log(wrapper.vm.todos)  
    // 斷言
    expect(wrapper.vm.todos.length).to.be.equal(2)
  })

  // 創建-- 增加 --測試用例
  it('測試增加功能', () => {
    // 通過mount 將組件渲染出來
    const wrapper = mount(todoMVC);
    // 1, 對newtodo進行賦值
    wrapper.setData({newtodo: 'test-word'})   
    // 2,對new-todo觸發回車事件
    wrapper.find('.newtodo').trigger('keyup.enter')  
    // 3,斷言,檢查todos中是否有數據增加
    expect(wrapper.vm.todos.length).to.be.equal(3)
    expect(wrapper.vm.todos[2].text).to.be.equal("test-word")
    console.log(wrapper.vm.todos)
  })

  // 創建-- 刪除 --測試用例
  it('測試刪除功能', () => {
    // 通過mount 將組件渲染出來
    const wrapper = mount(todoMVC);
    wrapper.find('.destroy').trigger('click')
    expect(wrapper.vm.todos.length).to.be.equal(1)
  })
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章