Vue-Jest 自動化測試基礎配置詳解
目前開發大型應用,測試是一個非常重要的環節,而在 Vue 項目中做單元測試可以用 Jest,Jest 是 facebook 推出的一款測試框架,集成了 Mocha, chai, jsdom, sinon 等功能,而且在 Vue 的腳手架中已經集成了 Jest,所以在 Vue 項目中使用 Jest 做單元測試是不二的選擇,從提供的例子上看都很簡單地配置并測試成功,然而在實際項目中有很多差異,我在測試自己的某個業務組件就報出很多錯誤,本文就總結一下自己的踩坑經歷,并幫助讀者快速解決配置中出現的問題。
安裝可以通過官方提供的 @vue/cli 直接創建 Vue 項目,然后選中 Unit Testing 這個選項
? Check the features needed for your project: ◉ Choose Vue version ◉ Babel❯◉ TypeScript ◯ Progressive Web App (PWA) Support ◉ Router ◉ Vuex ◯ CSS Pre-processors ◯ Linter / Formatter ◉ Unit Testing ◯ E2E Testing
然后在測試框架中選擇 Jest
? Pick a unit testing solution: Jest? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
Vue + Ts 的項目最終生成的 jest.config.js 配置文件長這樣,好像在告訴我們,我都給你們設置好了,直接用吧,然而針對項目,還需要手動去配置兼容,要不然會報出很多錯誤,無法進行下去。
module.exports = { preset: ’@vue/cli-plugin-unit-jest/presets/typescript-and-babel’}配置
先看看這個預設配置到底寫了什么,找到 @vue/cli-plugin-unit-jest/presets/typescript-and-babel 這個包,實際上這個輸出的配置如下:
module.exports = { moduleFileExtensions: [ // 測試的文件類型 ’js’, ’jsx’, ’json’, // tell Jest to handle *.vue files ’vue’, ’ts’, ’tsx’ ], transform: { // 轉化方式 // process *.vue files with vue-jest ’^.+.vue$’: require.resolve(’vue-jest’), ’.+.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$’: require.resolve(’jest-transform-stub’), ’^.+.jsx?$’: require.resolve(’babel-jest’), ’^.+.tsx?$’: require.resolve(’ts-jest’), }, transformIgnorePatterns: [’/node_modules/’], // 轉化時忽略 node_modules // support the same @ -> src alias mapping in source code moduleNameMapper: { // @符號 表示當前項目下的src ’^@/(.*)$’: ’<rootDir>/src/$1’ }, testEnvironment: ’jest-environment-jsdom-fifteen’, // serializer for snapshots snapshotSerializers: [ // 快照的配置 ’jest-serializer-vue’ ], testMatch: [ // 默認測試文件 ’**/tests/unit/**/*.spec.[jt]s?(x)’, ’**/__tests__/*.[jt]s?(x)’ ], // https://github.com/facebook/jest/issues/6766 testURL: ’http://localhost/’, watchPlugins: [ require.resolve(’jest-watch-typeahead/filename’), require.resolve(’jest-watch-typeahead/testname’) ], globals: { ’ts-jest’: { babelConfig: true } }}
其中比較重要的配置,也是我們比較多用來解決問題的配置:
moduleFileExtensions : 測試的文件類型,這里默認的配置基本涵蓋了文件類型,所以這里一般不需要改 transform : 轉化方式,匹配的文件要經過轉譯才能被識別,否則會報錯。 transformIgnorePatterns : 轉化忽略配置 moduleNameMapper : 模塊別名,如果有用到都要填寫進去常見錯誤SyntaxError : 語法錯誤,很可能是因為沒有進行轉化,比如下面的提示:
/Users/zhuangbing.cai/Documents/workspace/projects/wms-ui/node_modules/vue-runtime-helpers/dist/normalize-component.mjs:76 export default normalizeComponent; ^^^^^^ SyntaxError: Unexpected token ’export’
由于我們沒有對 .mjs 文件進行轉換導致了報錯,最快的解決方式就是在 transform 補充 .mjs 的轉化
transform: { ’^.+.mjs$’: ’babel-jest’}
只需要在對 .mjs 的文件,提供轉化方式即可。
另一種語法錯誤,是node_module 內的某些文件需要轉化,然而被 transformIgnorePatterns 配置忽略了。
Here’s what you can do: • To have some of your 'node_modules' files transformed, you can specify a custom 'transformIgnorePatterns' in your config. • If you need a custom transformation specify a 'transform' option in your config. • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the 'moduleNameMapper' config option. You’ll find more details and examples of these config options in the docs: https://jestjs.io/docs/en/configuration.html Details: /Users/zhuangbing.cai/Documents/workspace/projects/wms-ui/node_modules/vue-runtime-helpers/dist/normalize-component.mjs:76 export default normalizeComponent; ^^^^^^ SyntaxError: Unexpected token ’export’
圖中 vue-runtime-helpers 被用到了,然而因為 transformIgnorePatterns 的配置忽略了轉化,從而導致語法錯誤。解決方法就是改變 transformIgnorePatterns 的配置,如下:
transformIgnorePatterns: [ // 轉化時忽略 node_modules,但不包括 vue-runtime-helpers ’/node_modules/(?!(vue-runtime-helpers)/)’, ],
將 vue-runtime-helpers 排除后,轉化的時候就不會忽略它,從而解決語法報錯的問題。
Ts 類型錯誤
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option): src/views/inventory-map/__tests__/available.spec.ts:15:1 - error TS2304: Cannot find name ’beforeEach’. 15 beforeEach(() => { ~~~~~~~~~~ src/views/inventory-map/__tests__/available.spec.ts:19:1 - error TS2593: Cannot find name ’describe’. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig. 19 describe(’available-inventory-map’, () => { ~~~~~~~~ src/views/inventory-map/__tests__/available.spec.ts:20:3 - error TS2593: Cannot find name ’it’. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.
根據提示需要在 tscofig.json 中添加
{ 'compilerOptions': { 'types': [ 'webpack-env', 'jest' ], }}測試前的工作
在編寫測試用例前,我們需要 Jest 提供組件實例 vm 和渲染的 DOM 結構。對代碼邏輯、頁面效果的雙重測試保障,那么如何獲取到這個業務組件?
直接引用組件是不行的,因為你的業務組件需要的依賴很多,比如 UI 組件庫、工具函數、Vuex 的狀態等,所以首先我們需要處理好這些依賴。
處理依賴首先要知道要測試的這個業務組件依賴了哪些東西,全局的依賴可以參照 main.ts 或 main.js 入口文件處,其他可根據組件中的引用來判斷。有了依賴后如何在 Jest 中獲得組件實例?
Vue 提供了一個單元測試實用工具庫 - Vue Test Utils,編寫測試用例的時候可以用到它,首先利用 createLocalVue 創建一個 Vue 的類供你添加組件、混入和安裝插件而不會污染全局的 Vue 類, 接著將依賴引用進去。
const _localVue = createLocalVue();_localVue.use(Vuex);_localVue.use(UI);_localVue.use(i18nInstall);_localVue.component(’s-filter’, SFilter);_localVue.component(’w-table’, WTable);_localVue.directive(’xxx’, { inserted: (el, binding) => { .... },});export const localVue = _localVue;
這樣就拿到了一個包含依賴的 Vue 類,接著處理 Vuex,比如我們需要枚舉值
import enums from ’./enums’;export const systemStore = new Vuex.Store({ actions: {}, state: { enums: { systemEnums: enums, }, },});生成實例和 DOM
在得到 localVue 和 store 之后,我們要用它去生成結果,通過 mount 將組件渲染出來。
import { localVue, systemStore } from ’@/utils/unit-test/common’;import { mount } from ’@vue/test-utils’;require(’intersection-observer’); // 兼容jsdom不支持IntersectionObserverimport TaskList from ’../available-inventory-map/index.vue’; // 引用要測試的業務let store: any;beforeEach(() => { store = systemStore;});describe(’available-inventory-map’, () => { it(’篩選項測試’, () => { const renderer = createRenderer(); const wrapper = mount(TaskList, { localVue, store, attachToDocument: true, }); const html = wrapper.html(); // 得到完整的 html 結構 const vm = wrapper.vm; // 組件實例 console.log(html, vm); })}
將 localVue 和 store,通過 mount 最終得到實例和它的 DOM 結構。接下來就可以根據實例和 DOM 去編寫自己的測試用例啦。
總結本文主要介紹了在 Vue + Ts 項目中配置 Jest 自動化測試中遇到的問題總結,介紹基本配置和常見錯誤的解決方法,以及如何在開始編寫測試用例前得到完整的組件信息和 DOM。為接下來的用例編寫打下基礎。
引用Vue Test Utils
到此這篇關于Vue-Jest 自動化測試基礎配置詳解的文章就介紹到這了,更多相關Vue-Jest 自動化測試內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
