Vue單元測試

@vue/cli-plugin-unit-jest

unit-jest plugin for vue-clihtml

githubvue

vue add @vue/unit-jestgit

vue-cli-service test:unit [options] <regexForTestFiles>github

支持全部的Jest 命令行參數vue-cli

Jest 的配置項在項目根目錄下的jest.config.js文件中,或package.jsonjest字段中。json

依賴@vue/test-utils數組

Vue Test Utils

Vue Test Utils 是 Vue.js 官方的單元測試實用工具庫。app

github document工具

1. API

  • mount(component, options) 建立一個包含被掛載和渲染的Vue組件的Wrapper

1. Wrapper

屬性:單元測試

  • vm 只讀,該Vue實例
  • element 包裹器的根DOM節點
  • options.attachedToDocument 若是組件在渲染以後被添加到了文檔上則爲true
  • options.sync 若是掛載選項裏的 sync 不是 false 則爲真

方法:

方法 描述 參數 返回值
attributes 返回wrapper DOM 節點的特性對象 {string} key 可選 {[attribute: string]: any} | string
classes wrapper DOM 節點的class。返回 class 名稱的數組。或在提供 class 名的時候返回一個布爾值。 {string} className 可選 Array<{string}> | boolean
contains 判斷Wrapper是否包含了一個匹配選擇器的元素或組件 boolean
destroy 銷燬Vue組件實例
emitted 一個包含Wrapper vm觸發過的自定義事件對象,包含觸發的事件名稱,及每次觸發時的參數。 { [name: string]: Array<Array<any>> }
emittedByOrder 一個按觸發順序排列的Wrapper vm觸發過的自定義事件的數組 Array<{ name: string, args: Array<any> }>
exists 斷言 WrapperWrapperArray 是否存在。
find 匹配選擇器的第一個 DOM 節點或 Vue 組件的 Wrapper
findAll WrapperArray
html 返回WrapperDOM節點的HTML字符串
is 斷言WrapperDOM節點或vm與選擇器匹配 boolean
isEmpty 斷言Wrapper不包含子節點 boolean
isVisible 斷言Wrapper是否可見。若是有一個祖先元素擁有 display: none 或 visibility: hidden 樣式則返回 false。這能夠用於斷言一個組件是否被 v-show 所隱藏。
isVueInstance 斷言Wrapper是Vue實例
name 若是 Wrapper 包含一個 Vue 實例則返回組件名,不然返回 Wrapper DOM 節點的標籤名。
props 返回 Wrapper vm 的 props 對象。若是提供了 key,則返回這個 key 對應的值。 {[prop: string]: any} | any
setProps 設置Wrapper``vm的props並強制更新
setData 設置Wrapper vm的屬性。setData經過遞歸調用Vue.set生效
setMethods 設置Wrapper``vm的方法並強制更新
setChecked 設置 checkboxradio<input> 元素的 checked 值並更新 v-model 綁定的數據。 {Boolean} checked (默認值:true)
setSelected 選擇一個option元素並更新v-model綁定的數據
setValue 設置一個文本控件或select元素的值並更新v-model綁定的數據
text 返回的Wrapper的文本內容
trigger 在該 Wrapper DOM 節點上觸發一個事件。 {string} eventType 必填; {Object} options 可選

2. WrapperArray

3. 掛載選項

  • mount
  • shallowMount 只掛載一個組件而不會渲染其子組件

2. 經常使用技巧

咱們推薦測試撰寫爲斷言你的組件的公共接口,並在一個黑盒內部處理它。一個簡單的測試用例將會斷言一些輸入 (用戶的交互或 prop 的改變) 提供給某組件以後是否致使預期結果 (渲染結果或觸發自定義事件)。這樣的好處在於,即使該組件的內部實現已經隨時間發生了改變,只要你的組件的公共接口始終保持一致,測試就能夠經過。

下圖是

相關文章
相關標籤/搜索