簡介
單元測試是對軟件中的最小可測試單元進(jìn)行測試。(最小可測試單元是要有結(jié)果產(chǎn)出的。例如某個方法,單獨(dú)的某個操作)
單元測試其實(shí)是伴隨著敏捷開發(fā),它是對更快開發(fā)的一種追求。早發(fā)現(xiàn)錯誤比晚發(fā)現(xiàn)錯誤會更好,保證自己的代碼符合要求
一: 搭建基于 jest 的 vue 單元測試環(huán)境 零配置開箱即用 https://jestjs.io/zh-Hans/docs/getting-started
二: 使用 vue-test-util 提高測試編碼效率 https://v1.test-utils.vuejs.org/zh/guides/
(一) 手動搭建
編寫 jest 配置文件
// jest.conf.js
const path = require('path');
module.exports = {
rootDir: path.resolve(__dirname, '../../'), // 類似 webpack.context
moduleFileExtensions: [ // 類似 webpack.resolve.extensions
'js',
'json',
'vue',
],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1', // 類似 webpack.resolve.alias
},
transform: { // 類似 webpack.module.rules
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
},
setupFiles: ['<rootDir>/test/unit/setup'], // 類似 webpack.entry
coverageDirectory: '<rootDir>/test/unit/coverage', // 類似 webpack.output
collectCoverageFrom: [ // 類似 webpack 的 rule.include
'src/**/*.{js,vue}',
'!src/main.js',
'!src/router/index.js',
'!**/node_modules/**',
],
};
eslintrc.js
//
module.exports = {
env: {
browser: true,
es6: true,
jest: true
},
parserOptions: {
sourceType: 'module'
},
}
(二) 通過vue-cli5腳手架創(chuàng)建
vue-cli5
npm install -g @vue/cli
vue create 項(xiàng)目名
我們選擇 手動配置
上下鍵控制 空格選擇 這里選擇Babel轉(zhuǎn)碼器 Router Unit Testing 單元測試勾選上
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>( ) Babel //轉(zhuǎn)碼器,可以將ES6代碼轉(zhuǎn)為ES5代碼,從而在現(xiàn)有環(huán)境執(zhí)行。
( ) TypeScript// TypeScript是一個JavaScript(后綴.js)的超集(后綴.ts)包含并擴(kuò)展了 JavaScript 的語法,需要被編譯輸出為 JavaScript在瀏覽器運(yùn)行,目前較少人再用
( ) Progressive Web App (PWA) Support// 漸進(jìn)式Web應(yīng)用程序
( ) Router // vue-router(vue路由)
( ) Vuex // vuex(vue的狀態(tài)管理模式)
( ) CSS Pre-processors // CSS 預(yù)處理器(如:less、sass)
( ) Linter / Formatter // 代碼風(fēng)格檢查和格式化(如:ESlint)
( ) Unit Testing // 單元測試(unit tests)
( ) E2E Testing // e2e(end to end) 測試
選擇版本 2.x
是否開啟history模式 選擇否
選擇樣式預(yù)處理
語法檢測工具,這里我選擇ESLint + Standard config
Please pick a preset: Manually select features
Check the features needed for your project: Router, Vuex, CSS Pre-processors, Linter, Unit
Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Stylus
Pick a linter / formatter config: (Use arrow keys)
ESLint with error prevention only
ESLint + Airbnb config
> ESLint + Standard config
ESLint + Prettier
選擇語法檢查方式,這里我選擇fix和commit時候檢查檢測
Please pick a preset: Manually select features
Check the features needed for your project: Router, Vuex, CSS Pre-processors, Linter, Unit
Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Stylus
Pick a linter / formatter config: Prettier
Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
( ) Lint on save // 保存就檢測
>( ) Lint and fix on commit // fix和commit時候檢查
Unit Testing 勾選后 jest 回車安裝
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-proce
ssors, Linter, Unit
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback
in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported
by default): Sass/SCSS (with dart-sass)
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save
? Pick a unit testing solution: (Use arrow keys)
? Jest
Mocha + Chai
接下來會問你把babel,postcss,eslint這些配置文件放哪,這里隨便選,我選擇放在放package.json里
Vue CLI v5.0.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-proce
ssors, Linter, Unit
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback
in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported
by default): Sass/SCSS (with dart-sass)
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save
? Pick a unit testing solution: Jest
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
? In dedicated config files // 獨(dú)立文件放
In package.json // 放package.json里
? Save this as a preset for future projects? (y/N) // 是否記錄一下以便下次繼續(xù)使用這套配置。
等待安裝完成
100 packages are looking for funding
run `npm fund` for details
?? Invoking generators...
?? Installing additional dependencies...
added 145 packages from 105 contributors in 9.016s
139 packages are looking for funding
run `npm fund` for details
? Running completion hooks...
?? Generating README.md...
?? Successfully created project vue-test-util-02.
?? Get started with the following commands:
$ cd vue-test-util-02
$ npm run serve
運(yùn)行成功 接下來就 開始編寫我們的單元測試組件
找到 tests/unit 目錄
example.spec.js
import { shallowMount } from "@vue/test-utils"; // 可以通過 shallowMount 方法來創(chuàng)建包裹器
import HelloWorld from "@/components/HelloWorld.vue";
describe("HelloWorld.vue", () => {
it("renders props.msg when passed", () => {
const msg = "new message zyj";
// 現(xiàn)在掛載組件,你便得到了這個包裹器
const wrapper = shallowMount(HelloWorld, {
propsData: { msg },
});
expect(wrapper.text()).toMatch(msg);
});
});
describe塊允許我們對相關(guān)的測試進(jìn)行分組。當(dāng)我們運(yùn)行測試時,我們將看到控制臺中輸出的describe塊的名稱。
describe()接受一個字符串作為組件的名稱,并接受一個函數(shù)作為測試的參數(shù)。其實(shí),如果我們只有一個測試,我們不需要將它包裝在一個describe塊中。但是當(dāng)我們有多個測試時,用這種方式組織它們是有幫助的。
斷言的期望
在 Jest 中,我們使用斷言來確定我們期望測試返回的內(nèi)容是否與實(shí)際返回的內(nèi)容相匹配。具體來說,我們使用 Jest 的 expect() 方法來實(shí)現(xiàn)這一點(diǎn),該方法使我們能夠訪問許多 “匹配器” ,幫助我們將實(shí)際結(jié)果與預(yù)期結(jié)果進(jìn)行匹配。
斷言的語法基本上是這樣的:
expect(theResult).toBe(true) // expect(wrapper.text()).toMatch(msg);
在expect()方法內(nèi)部,我們將要測試的結(jié)果本身放入。然后,我們使用**匹配器(matcher)**來確定結(jié)果是否是我們預(yù)期的那樣。因此,在這里,我們使用通用的 Jest 匹配器toBe() 來說明:我們期望結(jié)果為真。
在編寫測試時,首先編寫一個您知道肯定會通過(或肯定會失?。┑臏y試是有幫助的。例如,如果我們說: expect(true).toBe(true) 我們知道這一定會通過。傳遞給expect()的結(jié)果是true,我們說我們期望這個結(jié)果是toBetrue 。所以如果我們運(yùn)行這些測試,我們知道它們一定會通過,因?yàn)?true == true。
現(xiàn)在已經(jīng)有了測試的分組,可以開始編寫這些單獨(dú)的測試(individual tests)
跑所有測試用例:運(yùn)行npm run test:uni
npm run test:unit 測試文件名
我們這邊使用 npm run test:unit example.spec.js文章來源:http://www.zghlxwxcb.cn/news/detail-412715.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-412715.html
到了這里,關(guān)于vue-cli5腳手架搭建項(xiàng)目過程詳解 -vue組件單元測試的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!