詳解在vue-test-utils中mock全局對象
vue-test-utils 提供了一種 mock 掉 Vue.prototype 的簡單方式,不但對測試用例適用,也可以為所有測試設置默認的 mock。
mocks 加載選項
mocks 加載選項 是一種將任何屬性附加到 Vue.prototype 上的方式。這通常包括:
- $store , for Vuex
- $router , for Vue Router
- $t , for vue-i18n
以及其他種種。
vue-i18n 的例子
我們來看一個 vue-i18n 的例子。雖然可以為每個測試用到 createLocalVue 并安裝 vue-i18n ,但那樣可能會讓事情難以處理并引入一堆樣板。首先,組件 <Bilingual> 用到了 vue-i18n :
<template> <div class="hello"> {{ $t("helloWorld") }} </div> </template> <script> export default { name: "Bilingual" } </script>
你先在另一個文件中弄好翻譯,然后通過 $t 引用,這就是 vue-i18n 的工作方式。在本次測試中,雖然并不會真正關心翻譯文件看起來什么樣,不過還是看一看這次用到的:
export default { "en": { helloWorld: "Hello world!" }, "ja": { helloWorld: "こんにちは、世界!" } }
基于這個 locale,正確的翻譯將被渲染出來。我們先不用 mock,嘗試在測試中渲染該組件:
import { shallowMount } from "@vue/test-utils" import Bilingual from "@/components/Bilingual.vue" describe("Bilingual", () => { it("renders successfully", () => { const wrapper = shallowMount(Bilingual) }) })
通過 yarn test:unit 運行測試將拋出一堆錯誤堆棧。若仔細端詳輸出則會發(fā)現(xiàn):
[Vue warn]: Error in config.errorHandler: "TypeError: _vm.$t is not a function"
這是因為我們并未安裝 vue-i18n ,所以全局的 $t 方法并不存在。我們試試 mocks 加載選項:
import { shallowMount } from "@vue/test-utils" import Bilingual from "@/components/Bilingual.vue" describe("Bilingual", () => { it("renders successfully", () => { const wrapper = shallowMount(Bilingual, { mocks: { $t: (msg) => msg } }) }) })
現(xiàn)在測試通過了! mocks 選項用處多多,而我覺得最最常用的正是開頭提到過的那三樣。
(譯注:通過這種方式就不能在單元測試中耦合與特定語言相關的內(nèi)容了,因為翻譯功能實際上已失效,也更無法處理可選參數(shù)等)
使用配置設置默認的 mocks
有時需要一個 mock 的默認值,這樣就不用為每個測試用例都設置一遍了。可以用 vue-test-utils 提供的 config API 來實現(xiàn)。還是 vue-i18n 的例子:
import VueTestUtils from "@vue/test-utils" VueTestUtils.config.mocks["mock"] = "Default Mock Value"
這個示例中用到了 Jest,所以我將把默認 mock 描述在 jest.init.js 文件中 -- 該文件會在測試運行前被自動加載。同時我也會導入并應用此前用于示例的翻譯對象。
//jest.init.js import VueTestUtils from "@vue/test-utils" import translations from "./src/translations.js" const locale = "en" VueTestUtils.config.mocks["$t"] = (msg) => translations[locale][msg]
現(xiàn)在盡管還是用了一個 mock 過的 $t 函數(shù),但會渲染一個真實的翻譯了。再次運行測試,這次移除了 mocks 加載選項并用 console.log 打印了 wrapper.html() 。
describe("Bilingual", () => { it("renders successfully", () => { const wrapper = shallowMount(Bilingual) console.log(wrapper.html()) }) })
測試通過,以下結構被渲染出來:
<div class="hello"> Hello world! </div>
(譯注:依然無法應付復雜的翻譯)
總結
本文論述了:
- 在測試用例中使用 mocks 以 mock 一個全局對象
- 用 config.mocks 設置默認的 mock
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue報錯Cannot?read?properties?of?undefined?(...)類型的解決辦法
這篇文章主要給大家介紹了關于vue報錯Cannot?read?properties?of?undefined?(...)類型的解決辦法,文中通過代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-04-04Vue.set()和this.$set()使用和區(qū)別
我們發(fā)現(xiàn)Vue.set()和this.$set()這兩個api的實現(xiàn)原理基本一模一樣,那么Vue.set()和this.$set()的區(qū)別是什么,本文詳細的介紹一下,感興趣的可以了解一下2021-06-06vue 實現(xiàn)axios攔截、頁面跳轉(zhuǎn)和token 驗證
這篇文章主要介紹了vue 實現(xiàn)axios攔截、頁面跳轉(zhuǎn)和token 驗證,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07