原文: itnext.io/testing-the…html
Vue 3 的 Composition API 的單元測試看起來會是什麼樣子呢?vue
爲了讓開發者們更早的嚐鮮 Composition API,Vue 團隊釋出了一個讓咱們能在 Vue 2 中使用的插件,能夠在 github.com/vuejs/compo… 找到它。react
本文速覽了新的 Composition API 如何玩轉官方的 Vue 組件單元測試庫 vue-test-utils
。劇透:用起來是同樣同樣的。git
測試一個用 Composition API 搭建的組件應該和測試一個標準組件沒有分別;由於咱們不測試其實現,而只是測試輸出(組件 是什麼,而非 如何爲之)。這篇文章將用一個簡單的例子,展現使用了 Composition API 的 Vue 2 組件,其測試策略和處理其餘組件時的何其相同。github
如下代碼或多或少地能夠算做 Composition API 界的 「Hello, World」 了。若是你有什麼不懂的,讀一下 vue-composition-api-rfc.netlify.com 或這篇文章 medium.com/js-dojo/com… ,再不行就谷bai歌du一下;總有不少可用的 Composition API 相關資源的。api
<template>
<div>
<div class="message">{{ uppercasedMessage }}</div>
<div class="count">
Count: {{ state.count }}
</div>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi)
import {
reactive,
computed
} from '@vue/composition-api'
export default {
name: 'CompositionApi',
props: {
message: {
type: String
}
},
setup(props) {
const state = reactive({
count: 0
})
const increment = () => {
state.count += 1
}
return {
state,
increment,
uppercasedMessage: computed(() => props.message.toUpperCase())
}
}
}
</script>
複製代碼
此處咱們將須要測試兩件事情:bash
state.count
加 1 嗎?測試 message 被穩當地渲染是小事一樁。咱們只消使用 propsData
設置屬性值便可,正如文檔 gist.github.com/components-… 中所描述的。app
import { shallowMount } from "@vue/test-utils"
import CompositionApi from "@/components/CompositionApi.vue"
describe("CompositionApi", () => {
it("renders a message", () => {
const wrapper = shallowMount(CompositionApi, {
propsData: {
message: "Testing the composition API"
}
})
expect(wrapper.find(".message").text()).toBe("TESTING THE COMPOSITION API")
})
})
複製代碼
果真很是簡單 -- 儘管咱們沒用組件方式,仍可使用一樣的 API 和一樣的測試策略。你應該可以整個改變實現,而不用碰測試代碼纔對。記住要基於給定的輸入(屬性、觸發的事件)測試輸出(一般是渲染過的 HTML),而非實現。async
寫一個測試去確保單擊按鈕後增長 state.count
一樣的簡單。注意該測試被標記爲 async
;關於爲什麼須要這樣作能夠參閱文章 《模擬用戶輸入》( gist.github.com/lmiller1990… )。單元測試
import { shallowMount } from "@vue/test-utils"
import CompositionApi from "@/components/CompositionApi.vue"
describe("CompositionApi", () => {
it("increments a count when button is clicked", async () => {
const wrapper = shallowMount(CompositionApi, {
propsData: { message: '' }
})
wrapper.find('button').trigger('click')
await wrapper.vm.$nextTick()
expect(wrapper.find(".count").text()).toBe("Count: 1")
})
})
複製代碼
不厭其煩地再解說一次 -- 咱們 trigger
了單擊事件,並斷言渲染過的 count
增長了。
本文演示瞭如何測試一個使用了 Composition API 的組件和測試一個傳統的 options API 組件時,不管是想法仍是概念,都是何其相同。要學習的要點在於,當編寫測試時,基於輸入和輸出作出斷言。vue-test-utils
並不關心你如何構成組件;全部既有的方法和 APIs 都能應用於 Composition API。這是個好事!
應該在無需修改單元測試的前提下,使用 Composition API 重構任何傳統的 Vue 組件。若是你發現本身在重構時須要更改測試,極可能就是以前測試了 具體實現,而非輸出。
雖然是個動人的新特性,但 Composition API 徹底是錦上添花的,因此不須要馬上去用它;可是不管你如何選擇,記住一個好的單元測試只斷言組件的最終狀態,而不用考慮其實現細節。
搜索 fewelife 關注公衆號
轉載請註明出處