前端自動化測試Vue中TDD和單元測試示例詳解
1、簡單用例入門
Vue 提供了 @vue/test-utils 來幫助我們進行單元測試,創(chuàng)建 Vue 項目的時候勾選測試選項會自動幫我們安裝
先來介紹兩個常用的掛載方法:
mount:會將組件以及組件包含的子組件都進行掛載shallowMount:淺掛載,只會掛載組件,忽略子組件
再來看一個簡單的測試用例:
import { shallowMount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";
describe("HelloWorld.vue", () => {
it("renders props.msg when passed", () => {
const msg = "new message";
const wrapper = shallowMount(HelloWorld, {
propsData: { msg }
});
expect(wrapper.props("msg")).toBe(msg);
});
});
shallowMount 會返回一個 wrapper,這個 wrapper 上面會包含很多幫助我們測試的方法,參考:v1.test-utils.vuejs.org/zh/api/wrap…
2、快照測試
測試用例寫法如下: 第一次測試會保存 wrapper 的快照,第二次會比較當前 wrapper 和快照的區(qū)別
describe("HelloWorld.vue", () => {
it("renders props.msg when passed", () => {
const msg = "new message";
const wrapper = shallowMount(HelloWorld, {
propsData: { msg }
});
expect(wrapper).toMatchSnapshot();
});
});
3、覆蓋率測試
覆蓋率測試是對測試完全程度的一個評估,測試覆蓋到的業(yè)務代碼越多,覆蓋率越高
在 jest.config.js 中我們可以設置 collectCoverageFrom,來設置需要進行覆蓋率測試的文件
我們可以測試所有的 .vue 文件,忽略 node_modules 下所有文件
要注意,在 Vue 中配置 jest,參考:v1.test-utils.vuejs.org/zh/guides/#…
然后添加一條 script 命令,就能進行測試了:
"test:unit": "vue-cli-service test:unit --coverage"
執(zhí)行命令會生成 coverage 文件夾,Icov-report/index.html 里會可視化展示我們的測試覆蓋率
4、結合 Vuex 進行測試
如果我們在組件中引入了 Vuex 狀態(tài)或者使用了相關方法
在測試用例里,掛載組件的時候只需要傳入 vuex 的 store 即可
import store from "@/store/index";
const wrapper = mount(HelloWorld, {
store
});以上就是前端自動化測試Vue中TDD和單元測試示例詳解的詳細內容,更多關于Vue TDD單元測試的資料請關注腳本之家其它相關文章!
相關文章
Vue自定義指令上報Google Analytics事件統(tǒng)計的方法
我們經常需要接入統(tǒng)計服務以方便運營,這篇文章主要介紹了Vue自定義指令上報Google Analytics事件統(tǒng)計的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
Vue3在css中使用v-bind綁定js/ts變量(在scss和less中使用方式)
v-bind是Vue.js中的一個核心指令,用于在Vue組件或DOM元素上綁定數據屬性,下面這篇文章主要給大家介紹了關于Vue3在css中使用v-bind綁定js/ts變量的相關資料,也可以在scss和less中使用方式,需要的朋友可以參考下2024-04-04

