vuecli3.0+vue-test-utils+mocha+karma生成單元測(cè)試
1、用vuecli3.0創(chuàng)建一個(gè)文件夾unit
vue create unit
可以選擇默認(rèn)配置驹吮,也可以根據(jù)自己的需要手動(dòng)配置
2、安裝相關(guān)依賴
- 安裝karma
npm install karma -g
并且在安裝的項(xiàng)目中使用
npm install karma --save-dev
需要全局安裝烙丛,可以使用命令行么伯。
安裝完成以后忍饰,命令行輸入 karma start
在瀏覽器輸入http://localhost:9876/
![此處輸入圖片的描述]
如果出現(xiàn)以上信息绝骚,表示karma已經(jīng)安裝成功耐版。
- karma配置
初始化karma配置文件karma.conf.js- ctrl+c 結(jié)束剛才啟動(dòng)的Karma
-
在命令行輸入karma init
- 接下就是一段詢問(wèn)關(guān)于配置的問(wèn)題。(ps:karma.conf.js配置可以自己修改压汪,這里是快速生成配置)
Which testing framework do you want to use?(你想要使用哪個(gè)測(cè)試框架粪牲?)
默認(rèn)是jasmine。(如果你想用其他可以自己修改)止剖,直接回車下一步Do you want to use Require.js ? (你要使用Require.js嗎腺阳?)
This will add Require.js plugin. (這將添加Require.js插件。)
Press tab to list possible options. Enter to move to the next question. (按選項(xiàng)卡列出可能的選項(xiàng)穿香。 輸入轉(zhuǎn)到下一個(gè)問(wèn)題亭引。)
默認(rèn)是no。(現(xiàn)在都在使用webpack打包皮获,這也是為什么你肯定奇怪的地方焙蚓,單元測(cè)試為什么要用webpack) ,直接回車下一步Do you want to capture any browsers automatically ? (你想要在哪些瀏覽器里面運(yùn)行)
Press tab to list possible options. Enter empty string to move to the next question.(和上面一樣)
默認(rèn)是Chrome洒宝。(你可以添加更多瀏覽器回車就是填寫下一個(gè)瀏覽器名稱购公,必須是你電腦安裝的瀏覽器,最好還是去karma.conf.js添加直觀一些)雁歌,直接按2次回車下一步-
What is the location of your source and test files ?(測(cè)試文件的位置是什么宏浩?)
You can use glob patterns, eg. "js/.js" or "test//Spec.js".(你可以使用glob模式,例如靠瞎。 “js / .js”或“test / ** / * Spec.js”)
Enter empty string to move to the next question.(輸入空字符串移動(dòng)到下一個(gè)問(wèn)題绘闷。)
默認(rèn)是空,這個(gè)是配置你的單元測(cè)試用例的文件较坛,根據(jù)自己項(xiàng)目和喜好,你可以把測(cè)試用例文件和當(dāng)前被文件放在一起扒最,例如angular-cli就是這樣的丑勤。也可以單獨(dú)分離放到test文件下,github大量的npm包都是這樣的吧趣。我這里就學(xué)angular-cli做法法竞,填寫:tests/****/.spec.js,就是說(shuō)tests文件夾下的所有.spec.js后綴都是t測(cè)試用例文件强挫〔戆裕回車下一步
vue生成的目錄里已經(jīng)有單元測(cè)試的文件夾,目錄機(jī)構(gòu)如下:
如果不想建俯渤,可以直接下一步呆细,等會(huì)到karma.conf.js修改。 Should any of the files included by the previous patterns be excluded ?(是否應(yīng)排除某些包含的任何文件八匠?)
You can use glob patterns, eg. "/.swp". (您可以使用glob模式絮爷,例如趴酣。“/.SWP”坑夯。)
這是為了性能優(yōu)化岖寞,排除那些文件不需要去監(jiān)聽,加快運(yùn)行速度柜蜈。如果你不確定要排除哪些文件仗谆,可以去karma.conf.js修改。我就直接直接下一步了淑履。Do you want Karma to watch all the files and run the tests on change ? (你想要Karma來(lái)監(jiān)聽所有的文件隶垮,并在變化中運(yùn)行測(cè)試嗎?)
Press tab to list possible options. (按選項(xiàng)卡列出可能的選項(xiàng)鳖谈。)
默認(rèn)yes岁疼,它的意思你寫完了.spec.js后綴文件會(huì)自動(dòng)運(yùn)行測(cè)試,等我們把Karma跑起來(lái)缆娃,在自動(dòng)運(yùn)行捷绒。
這里no。
這就生成出來(lái)了配置
找一款你順手的編輯器打開它贯要,(我的用vscode)
-
接下來(lái)就說(shuō)關(guān)于依賴插件plugins
需要可以打開Chrome瀏覽器的插件 npm install karma-chrome-launcher --save-dev
需要可以運(yùn)行mocha的插件 npm install karma-mocha --save-dev
需要可以運(yùn)行webpack的插件 npm install karma-webpack --save-dev
需要可以顯示sourcemap的插件 npm install karma-sourcemap-loader --save-dev
需要可以顯示測(cè)試代碼覆蓋率的插件 npm install karma-coverage-istanbul-reporter --save-dev
插件就先安裝這么多暖侨,后面需要在安裝,可以這樣一起安裝:npm install karma-chrome-launcher karma-mocha karma-webpack karma-sourcemap-loader karma-coverage-istanbul-reporter --save-dev
把插件寫到karma.conf.js配置里面去
我們先只需要前2個(gè)崇渗,后面注釋起來(lái)字逗,讓karma能隨時(shí)跑起來(lái)。
然后去package.json 配置一個(gè)npm命令宅广,編輯器或者ide可以直接運(yùn)行npm命令葫掉。
我們karma配置可以運(yùn)行起來(lái),點(diǎn)擊瀏覽器的debug按鈕跟狱,在新頁(yè)面中右鍵檢查俭厚,看到報(bào)錯(cuò)如下:
是因?yàn)闉g覽器無(wú)法識(shí)別es6語(yǔ)法導(dǎo)致的,那么我們需要安裝babel的相關(guān)依賴解決這個(gè)問(wèn)題驶臊,babel的依賴包盡量保持一致挪挤,這里我們使用7.*版本
npm i -D @babel/core @babel/preset-env babel-loader babel-plugin-istanbul @babel/plugin-syntax-dynamic-import
同時(shí)需要安裝webpack,這里需要注意关翎,
<p style="color:red">webpack4.版本需要安裝的vue-loader也是14.扛门,否則會(huì)報(bào)錯(cuò)無(wú)法識(shí)別vue語(yǔ)法</p>
<p style="color:red">babel版本要一致</p>
我們?cè)诟夸浵滦陆╞abel配置文件:.babelrc文件,輸入內(nèi)容:
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"@babel/plugin-syntax-dynamic-import"
]
}
<p style="color:red">在karma.conf.js文件對(duì)webpack配置識(shí)別vue路徑別名@</p>
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
'static': path.resolve(__dirname, '../static') // 增加這一行代碼
}
}
我們對(duì)比一下安裝的所有依賴:
package.json文件如下:
{
"name": "unit",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test:unit": "vue-cli-service test:unit",
"unit": "karma start"
},
"dependencies": {
"vue": "^2.5.17",
"vue-router": "^3.0.1",
"vuex": "^3.0.1",
"vue-loader": "^14.2.2"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.2.3",
"@vue/cli-plugin-babel": "^3.2.0",
"@vue/cli-plugin-unit-mocha": "^3.2.0",
"@vue/cli-service": "^3.2.0",
"@vue/test-utils": "^1.0.0-beta.20",
"babel-loader": "^8.0.4",
"babel-plugin-istanbul": "^5.1.0",
"chai": "^4.1.2",
"karma": "^3.1.4",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage-istanbul-reporter": "^2.0.4",
"istanbul-instrumenter-loader": "^3.0.1",
"karma-mocha": "^1.3.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^3.0.5",
"node-sass": "^4.9.0",
"sass-loader": "^7.0.1",
"vue-template-compiler": "^2.5.17",
"webpack": "^4.28.0",
"webpack-dev-server": "^3.1.13"
}
}
配置完成后的karma.conf.js文件如下:
// Karma configuration
// Generated on Thu Dec 20 2018 22:30:40 GMT+0800 (CST)
const path = require('path')
function resolve (dir) {
return path.join(__dirname, dir)
}
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'tests/**/*.spec.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'tests/**/*.spec.js': ['webpack', 'sourcemap']
},
plugins: [
'karma-chrome-launcher',
'karma-mocha',
'karma-webpack',
'karma-sourcemap-loader',
'karma-coverage-istanbul-reporter'
],
webpack: {
devtool: 'inline-source-map',
module: {
rules: [{
test: /\.js$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: { esModules: true }
},
enforce: 'pre',
exclude: /node_modules|\.spec\.js$/
}, {
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-syntax-dynamic-import', 'istanbul']
}
}, {
test: /\.vue$/,
loader: 'vue-loader'
}]
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
'static': path.resolve(__dirname, '../static') // 增加這一行代碼
}
}
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['coverage-istanbul'],
// 配置覆蓋率報(bào)告的查看方式配置
coverageIstanbulReporter: {
// 可以用什么形式展示 支持以下格式:clover纵寝、cobertura论寨、html、json-summary、json政基、lcov贞铣、lcovonly、none沮明、teamcity辕坝、text-lcov、text-summary荐健、text
// 可以看連接 : https://github.com/istanbuljs/istanbul-reports/tree/590e6b0089f67b723a1fdf57bc7ccc080ff189d7/lib
reports: ['html', 'text-summary'],
// 結(jié)果存放的位置
dir: 'coverage/',
// 如果使用webpack和預(yù)加載器酱畅,可以繞過(guò)webpack打破源路徑
fixWebpackSourcePaths: true,
// 停止輸出消息,如`File [$ {filename}]忽略江场,沒(méi)有任何東西可以映射
skipFilesWithNoCoverage: true,
// 大多數(shù)記錄接受額外的配置選項(xiàng)纺酸。 你可以通過(guò)`report-config`選項(xiàng)傳遞這些
'report-config': {
// 配置html
html: {
// 輸出到 ./coverage/html
subdir: 'html'
}
}
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
至此,配置完成址否,全部覆蓋餐蔬,ok完工