對(duì) Vue-Router 進(jìn)行單元測(cè)試的方法
由于路由通常會(huì)把多個(gè)組件牽扯到一起操作,所以一般對(duì)其的測(cè)試都在 端到端/集成 階段進(jìn)行,處于測(cè)試金字塔的上層。不過(guò),做一些路由的單元測(cè)試還是大有益處的。
對(duì)于與路由交互的組件,有兩種測(cè)試方式:
- 使用一個(gè)真正的 router 實(shí)例
- mock 掉 $route 和 $router 全局對(duì)象
因?yàn)榇蠖鄶?shù) Vue 應(yīng)用用的都是官方的 Vue Router,所以本文會(huì)談?wù)勥@個(gè)。
創(chuàng)建組件
我們會(huì)弄一個(gè)簡(jiǎn)單的 <App>,包含一個(gè) /nested-child 路由。訪問(wèn) /nested-child 則渲染一個(gè) <NestedRoute> 組件。創(chuàng)建 App.vue 文件,并定義如下的最小化組件:
<template> <div id="app"> <router-view /> </div> </template> <script> export default { name: 'app' } </script>
<NestedRoute> 同樣迷你:
<template> <div>Nested Route</div> </template> <script> export default { name: "NestedRoute" } </script>
現(xiàn)在定義一個(gè)路由:
import NestedRoute from "@/components/NestedRoute.vue" export default [ { path: "/nested-route", component: NestedRoute } ]
在真實(shí)的應(yīng)用中,一般會(huì)創(chuàng)建一個(gè) router.js 文件并導(dǎo)入定義好的路由,寫出來(lái)一般是這樣的:
import Vue from "vue" import VueRouter from "vue-router" import routes from "./routes.js" Vue.use(VueRouter) export default new VueRouter({ routes })
為避免調(diào)用 Vue.use(...) 污染測(cè)試的全局命名空間,我們將會(huì)在測(cè)試中創(chuàng)建基礎(chǔ)的路由;這讓我們能在單元測(cè)試期間更細(xì)粒度的控制應(yīng)用的狀態(tài)。
編寫測(cè)試
先看點(diǎn)代碼再說(shuō)吧。我們來(lái)測(cè)試 App.vue,所以相應(yīng)的增加一個(gè) App.spec.js:
import { shallowMount, mount, createLocalVue } from "@vue/test-utils" import App from "@/App.vue" import VueRouter from "vue-router" import NestedRoute from "@/components/NestedRoute.vue" import routes from "@/routes.js" const localVue = createLocalVue() localVue.use(VueRouter) describe("App", () => { it("renders a child component via routing", () => { const router = new VueRouter({ routes }) const wrapper = mount(App, { localVue, router }) router.push("/nested-route") expect(wrapper.find(NestedRoute).exists()).toBe(true) }) })
照例,一開始先把各種模塊引入我們的測(cè)試;尤其是引入了應(yīng)用中所需的真實(shí)路由。這在某種程度上很理想 -- 若真實(shí)路由一旦掛了,單元測(cè)試就失敗,這樣我們就能在部署應(yīng)用之前修復(fù)這類問(wèn)題。
可以在 <App> 測(cè)試中使用一個(gè)相同的 localVue,并將其聲明在第一個(gè) describe 塊之外。而由于要為不同的路由做不同的測(cè)試,所以把 router 定義在 it 塊里。
另一個(gè)要注意的是這里用了 mount 而非 shallowMount。如果用了 shallowMount,則 <router-link> 就會(huì)被忽略,不管當(dāng)前路由是什么,渲染的其實(shí)都是一個(gè)無(wú)用的替身組件。
為使用了 mount 的大型渲染樹做些變通
使用 mount 在某些情況下很好,但有時(shí)卻是不理想的。比如,當(dāng)渲染整個(gè) <App> 組件時(shí),正趕上渲染樹很大,包含了許多組件,一層層的組件又有自己的子組件。這么些個(gè)子組件都要觸發(fā)各種生命周期鉤子、發(fā)起 API 請(qǐng)求什么的。
如果你在用 Jest,其強(qiáng)大的 mock 系統(tǒng)為此提供了一個(gè)優(yōu)雅的解決方法??梢院?jiǎn)單的 mock 掉子組件,在本例中也就是 <NestedRoute>。使用了下面的寫法后,以上測(cè)試也將能通過(guò):
jest.mock("@/components/NestedRoute.vue", () => ({ name: "NestedRoute", render: h => h("div") }))
使用 Mock Router
有時(shí)真實(shí)路由也不是必要的?,F(xiàn)在升級(jí)一下 <NestedRoute>,讓其根據(jù)當(dāng)前 URL 的查詢字符串顯示一個(gè)用戶名。這次我們用 TDD 實(shí)現(xiàn)這個(gè)特性。以下是一個(gè)基礎(chǔ)測(cè)試,簡(jiǎn)單的渲染了組件并寫了一句斷言:
import { shallowMount } from "@vue/test-utils" import NestedRoute from "@/components/NestedRoute.vue" import routes from "@/routes.js" describe("NestedRoute", () => { it("renders a username from query string", () => { const username = "alice" const wrapper = shallowMount(NestedRoute) expect(wrapper.find(".username").text()).toBe(username) }) })
然而我們并沒(méi)有 <div class="username"> ,所以一運(yùn)行測(cè)試就會(huì)報(bào)錯(cuò):
tests/unit/NestedRoute.spec.js
NestedRoute
✕ renders a username from query string (25ms)● NestedRoute › renders a username from query string
[vue-test-utils]: find did not return .username, cannot call text() on empty Wrapper
來(lái)更新一下 <NestedRoute>:
<template> <div> Nested Route <div class="username"> {{ $route.params.username }} </div> </div> </template>
現(xiàn)在報(bào)錯(cuò)變?yōu)榱耍?/p>
tests/unit/NestedRoute.spec.js
NestedRoute
✕ renders a username from query string (17ms)● NestedRoute › renders a username from query string
TypeError: Cannot read property 'params' of undefined
這是因?yàn)?$route 并不存在。 我們當(dāng)然可以用一個(gè)真正的路由,但在這樣的情況下只用一個(gè) mocks 加載選項(xiàng)會(huì)更容易些:
it("renders a username from query string", () => { const username = "alice" const wrapper = shallowMount(NestedRoute, { mocks: { $route: { params: { username } } } }) expect(wrapper.find(".username").text()).toBe(username) })
這樣測(cè)試就能通過(guò)了。在本例中,我們沒(méi)有做任何的導(dǎo)航或是和路由的實(shí)現(xiàn)相關(guān)的任何其他東西,所以 mocks 就挺好。我們并不真的關(guān)心 username 是從查詢字符串中怎么來(lái)的,只要它出現(xiàn)就好。
測(cè)試路由鉤子的策略
Vue Router 提供了多種類型的路由鉤子, 稱為 “navigation guards”。舉兩個(gè)例子如:
- 全局 guards (router.beforeEach)。在 router 實(shí)例上聲明
- 組件內(nèi) guards,比如 beforeRouteEnter。在組件中聲明
要確保這些運(yùn)作正常,一般是集成測(cè)試的工作,因?yàn)樾枰粋€(gè)使用者從一個(gè)理由導(dǎo)航到另一個(gè)。但也可以用單元測(cè)試檢驗(yàn)導(dǎo)航 guards 中調(diào)用的函數(shù)是否正常工作,并更快的獲得潛在錯(cuò)誤的反饋。這里列出一些如何從導(dǎo)航 guards 中解耦邏輯的策略,以及為此編寫的單元測(cè)試。
全局 guards
比方說(shuō)當(dāng)路由中包含 shouldBustCache 元數(shù)據(jù)的情況下,有那么一個(gè) bustCache 函數(shù)就應(yīng)該被調(diào)用。路由可能長(zhǎng)這樣:
//routes.js import NestedRoute from "@/components/NestedRoute.vue" export default [ { path: "/nested-route", component: NestedRoute, meta: { shouldBustCache: true } } ]
之所以使用 shouldBustCache 元數(shù)據(jù),是為了讓緩存無(wú)效,從而確保用戶不會(huì)取得舊數(shù)據(jù)。一種可能的實(shí)現(xiàn)如下:
//router.js import Vue from "vue" import VueRouter from "vue-router" import routes from "./routes.js" import { bustCache } from "./bust-cache.js" Vue.use(VueRouter) const router = new VueRouter({ routes }) router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.shouldBustCache)) { bustCache() } next() }) export default router
在單元測(cè)試中,你可能想導(dǎo)入 router 實(shí)例,并試圖通過(guò) router.beforeHooks[0]() 的寫法調(diào)用 beforeEach;但這將拋出一個(gè)關(guān)于 next 的錯(cuò)誤 -- 因?yàn)闆](méi)法傳入正確的參數(shù)。針對(duì)這個(gè)問(wèn)題,一種策略是在將 beforeEach 導(dǎo)航鉤子耦合到路由中之前,解耦并單獨(dú)導(dǎo)出它。做法是這樣的:
//router.js export function beforeEach((to, from, next) { if (to.matched.some(record => record.meta.shouldBustCache)) { bustCache() } next() } router.beforeEach((to, from, next) => beforeEach(to, from, next)) export default router
再寫測(cè)試就容易了,雖然寫起來(lái)有點(diǎn)長(zhǎng):
import { beforeEach } from "@/router.js" import mockModule from "@/bust-cache.js" jest.mock("@/bust-cache.js", () => ({ bustCache: jest.fn() })) describe("beforeEach", () => { afterEach(() => { mockModule.bustCache.mockClear() }) it("busts the cache when going to /user", () => { const to = { matched: [{ meta: { shouldBustCache: true } }] } const next = jest.fn() beforeEach(to, undefined, next) expect(mockModule.bustCache).toHaveBeenCalled() expect(next).toHaveBeenCalled() }) it("busts the cache when going to /user", () => { const to = { matched: [{ meta: { shouldBustCache: false } }] } const next = jest.fn() beforeEach(to, undefined, next) expect(mockModule.bustCache).not.toHaveBeenCalled() expect(next).toHaveBeenCalled() }) })
最主要的有趣之處在于,我們借助 jest.mock,mock 掉了整個(gè)模塊,并用 afterEach 鉤子將其復(fù)原。通過(guò)將 beforeEach 導(dǎo)出為一個(gè)已結(jié)耦的、普通的 Javascript 函數(shù),從而讓其在測(cè)試中不成問(wèn)題。
為了確定 hook 真的調(diào)用了 bustCache 并且顯示了最新的數(shù)據(jù),可以使用一個(gè)諸如 Cypress.io 的端到端測(cè)試工具,它也在應(yīng)用腳手架 vue-cli 的選項(xiàng)中提供了。
組件 guards
一旦將組件 guards 視為已結(jié)耦的、普通的 Javascript 函數(shù),則它們也是易于測(cè)試的。假設(shè)我們?yōu)?<NestedRoute> 添加了一個(gè) beforeRouteLeave hook:
//NestedRoute.vue <script> import { bustCache } from "@/bust-cache.js" export default { name: "NestedRoute", beforeRouteLeave(to, from, next) { bustCache() next() } } </script>
對(duì)在全局 guard 中的方法照貓畫虎就可以測(cè)試它了:
// ... import NestedRoute from "@/compoents/NestedRoute.vue" import mockModule from "@/bust-cache.js" jest.mock("@/bust-cache.js", () => ({ bustCache: jest.fn() })) it("calls bustCache and next when leaving the route", () => { const next = jest.fn() NestedRoute.beforeRouteLeave(undefined, undefined, next) expect(mockModule.bustCache).toHaveBeenCalled() expect(next).toHaveBeenCalled() })
這樣的單元測(cè)試行之有效,可以在開發(fā)過(guò)程中立即得到反饋;但由于路由和導(dǎo)航 hooks 常與各種組件互相影響以達(dá)到某些效果,也應(yīng)該做一些集成測(cè)試以確保所有事情如預(yù)期般工作。
總結(jié)
本文講述了:
- 測(cè)試由 Vue Router 條件渲染的組件
- 用 jest.mock 和 localVue 去 mock Vue 組件
- 從 router 中解耦全局導(dǎo)航 guard 并對(duì)其獨(dú)立測(cè)試
- 用 jest.mock 來(lái) mock 一個(gè)模塊
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決Vue運(yùn)行項(xiàng)目報(bào)錯(cuò)proxy?error:?could?not?proxy?request
這篇文章主要給大家介紹了關(guān)于如何解決Vue運(yùn)行項(xiàng)目報(bào)錯(cuò)proxy?error:could?not?proxy?request的相關(guān)資料,Proxy Error指的是代理服務(wù)器無(wú)法正確處理請(qǐng)求的錯(cuò)誤,需要的朋友可以參考下2023-08-08vue 組件的封裝之基于axios的ajax請(qǐng)求方法
今天小編就為大家分享一篇vue 組件的封裝之基于axios的ajax請(qǐng)求方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08vue2封裝webSocket的實(shí)現(xiàn)(開箱即用)
在Vue2中,可以使用WebSocket實(shí)時(shí)通信,本文主要介紹了vue2封裝webSocket的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08基于Vue3實(shí)現(xiàn)掃碼槍掃碼并生成二維碼實(shí)例代碼
vue3生成二維碼的方式有很多種,下面這篇文章主要給大家介紹了關(guān)于如何基于Vue3實(shí)現(xiàn)掃碼槍掃碼并生成二維碼的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06Vue?列表過(guò)濾與排序的實(shí)現(xiàn)
這篇文章主要介紹了Vue?列表過(guò)濾與排序的實(shí)現(xiàn),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值需要的小伙伴可以參考一下2022-05-05vue-cli 引入jQuery,Bootstrap,popper的方法
這篇文章主要介紹了vue-cli 引入jQuery,Bootstrap,popper的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-09