主要內容:
- 簡單的斷言
- 寫可測試的組件
- 斷言的異步更新
Vue CLI已經爲單元測試構建了操作項,使用Jest或Mocha開箱即用。我們也提供了官方的單元測試庫Vue Test Utils,爲自定義配置提供了更爲細節的指導。
簡單的斷言
你不必爲了組件的可測試性提供任何特殊操作,導出原生的操作即可:
<template>
<span>{{ message }}<span>
</template>
<script>
export default {
data () {
return {
message: 'hello!'
}
},
created () {
this.message = 'bye!'
}
}
<script>
然後隨着Vue的導入組件的選項,你可以寫一些常用的斷言(這裏我們使用Jasmine/Jest風格的expect
作爲例子):
// 導入Vue和被測試的組件
import Vue from 'vue'
import MyComponent from 'path/to/MyComponent.vue'
// 這是一些Jasmine 2.0 測試,不過你可以使用能使用任何測試運行器/斷言庫
describe('MyComponent', () => {
// 檢查原生組件項
it('has a created hook', () => {
expect(typeof MyComponent.created).toBe('function')
})
// 在原生組件項中計算函數的結果
it('sets the correct default data', () => {
expect(typeof MyComponent.data).toBe('function')
const defaultData = MyComponent.data()
expect(defaultData.message).toBe('hello!')
})
// 在mount中檢查組件實例
it('correctly sets the message when created', () => {
const vm = new Vue(MyComponent).$mount()
expect(vm.message).toBe('bye!')
})
// 掛載一個實例並檢查渲染輸出
it('renders the correct message', () => {
const Constuctor = Vue.extend(MyComponent)
const vm = new Constructor().$mount()
expect(vm.$el.textContent).toBe('bye!')
})
}
編寫可被測試的組件
一個組件的渲染輸出主要由它所接收的props決定,如果一個組件的渲染輸出只依賴於它的props,那麼測試將變得簡單,就好像斷言純函數的不同參數的返回值。
<template>
<p>{{ msg }}</p>
</template>
<script>
export default {
props: ['msg']
}
</script>
你能使用propsData操作項用不同的props去斷言渲染的輸出:
import Vue from 'vue'
import MyComponent from './MyComponent.vue'
// 幫助函數:加載和返回渲染文本
function getRederedText (Component, propsData) {
const Constructor = Vue.extend(Component)
const vm = new Constructor({ propsData: propsData }).$mount()
return vm.$el.textContent
}
describe('MyComponent', () => {
it('renders correctly with different props', () => {
expect(getRenderedText(MyComponent, {
msg: 'Hello'
})).toBe('Hello')
expect(getRenderedText(MyComponent, {
msg: 'Bye'
})).toBe('Bye')
})
})
斷言異步更新
由於Vue執行異步更新DOM performs DOM updates asynchronously,一些狀態改變導致的DOM更新的斷言必須在Vue.nextTick
回調中進行:
// 狀態更新之後,檢查生成的HTML
it('updates the rendered message when vm.message updates', done => {
const vm = new Vue(MyComponent).$mount()
vm.message = 'foo'
// 在斷言DOM更新之前,狀態改變之後等待一個“tick”
Vue.nextTick(() => {
expect(vm.$el.textContent).toBe('foo')
done()
})
})
對於更深入的Vue單元測試內容,移步Vue Text Utils和我們關於unit testing vue components cookbook的文章。