一.前言
此文檔爲前端自動化單元測試框架 Karma
的搭建以及使用文檔。
二.準備環境
先列出我們此次搭建測試框架 Karma
必須的環境和包。
1. node.js (node 引擎)
2. npm (node 包管理器)
3. cnpm(可選) (淘寶鏡像)
4. karma (提供 web 服務和瀏覽器適配)
5. mocha (單元測試框架)
6. chai (斷言庫)
6. requirejs (提供非commonjs規範的模塊加載)
7. karma-mocha karma-chai karma-requirejs (karma 中對應的包)
8. karma-chrome-launcher karma-ie-launcher (karma 中的瀏覽器適配包)
9. karma-mocha-reporter (karma 中的 mocha 終端測試報告)
10. karma-htmlfile-reporter (karam 生成 html 格式的測試報告文件)
三.安裝步驟
1. 安裝 node
和 npm
進入node官網,根據你的操作系統選擇對應的安裝包。安裝時記得添加選擇默認添加環境變量和安裝npm
。
安裝完成後打開gitbash
輸入以下命令測試是否安裝成功:
$ node -v
v10.14.1
$ npm -v
6.4.1
2. 安裝 cnpm
此爲npm
的淘寶鏡像,爲了解決npm
下載包網速過慢的問題。請在gitbash
中輸入以下命令:
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
完成後輸入以下命令測試cnpm
是否安裝成功:
cnpm -v
3.初始化 package.json
首先,在項目內新建一個文件夾 /test
。(與static
,templates
平級)。此時我們有以下目錄結構:
由於這是我已經配置好的目錄結構,各位可以先不用關心細節,我們從空的/test
文件夾開始。
在 gitbash
中進入 /test
目錄,然後輸入命令:
$ npm init -y
會出現一個名爲 package.json
的 json
文件,文件內容如下:
4. 安裝 karma
和 karma-cli
什麼是 karma
這種問題大家可以自行去Karma官網自行查看。
我們回到剛剛那個 gitbash
目錄,輸入以下命令:
$ cnpm install karma-cli -g
$ cnpm install karma -D
安裝好之後輸入 karma --version
來查看是否安裝成功。
5.安裝 package.json
中的依賴
打開你的 package.json
文件,此時它的內容如下:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"karma": "^4.0.0"
}
}
devDependencies
中是你的依賴包,現在你要做的就是用下面這個 json
中的內容去替換你的 package.json
內容。
{
"name": "test-project2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"chai": "^4.2.0",
"karma": "^4.0.0",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-htmlfile-reporter": "^0.3.7",
"karma-ie-launcher": "^1.0.0",
"karma-mocha": "^1.3.0",
"karma-mocha-reporter": "^2.2.5",
"karma-requirejs": "^1.1.0",
"mocha": "^5.2.0",
"requirejs": "^2.3.6"
}
}
替換完了後,回到 gitbash
中輸入:
$ cnpm install
安裝完成後即可。
5.初始化 karma.conf.js
配置文件
現在我們需要配置一下 karma
的配置文件:
$ karma init
然後 karma
會讓我們配置一些選項,你可以按下面這張圖來配:
完成後我們可以在 /test
文件夾根目錄裏看到一個 karma.conf.js
文件。
注意,在 windows
操作系統下使用 gitbash
進行 karma init
時會報以下錯誤:
這時你切換到 windows
的默認終端來執行命令就好。
由於不同的項目文件目錄的配置不同,所以提供一個標準的 karma.conf.js
配置不是一件現實的事情,它需要對 karma.conf.js
文件中的 files
屬性進行一些改變。下面我提供一個控制中心 RC2
版本的 karma.conf.js
配置:
// Karma configuration
// Generated on Mon Jan 28 2019 14:56:31 GMT+0800 (GMT+08:00)
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', 'requirejs', 'chai'],
// list of files / patterns to load in the browser
files: [
{ pattern: 'lib/*.js', included: true },
{ pattern: '../static/js/common/*.js', included: true },
{ pattern: 'unit-test/**/*.spec.js', included: false },
'./test-main.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: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha', 'html'],
mochaReporter: {
output: 'autowatch'
},
htmlReporter: {
outputFile: 'reproter/units.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// web server port
port: 9877,
// 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', 'IE'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
6.設置 requirejs
入口文件
通常來說我們需要在 A.js
中引入 B.js
中的一個函數,需要這樣:
const add = require('./B.js');
add(1,2) // logs 3
B.js
中的內容應該如下:
exports.add = function(){
var sum = 0;
for(let i = 0; i < arguments.length; i++){
sum += arguments[i];
}
return sum;
}
具體規則大家可以自行去查閱commonJS規範
。
但是我們現在不具備這個條件,前端代碼並不是commonjs
格式,所以我們需要引入requirejs
來解決這個問題。
在 /test
文件夾下新建 test-main.js
文件,內容如下:
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
// example of using a couple of path translations (paths), to allow us to refer to different library dependencies, without using relative paths
paths: {
},
// example of using a shim, to load non AMD libraries (such as underscore)
shim: {
'underscore': {
exports: '_'
}
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
7.進行簡單的 unit test
我以控制中心RC2
的目錄結構爲例,在 /webui/static/js/common
下有個datahandle.js
文件,我們取其中的一個dataHandle.cutLargeNum()
函數來進行測試。
首先看下目前 /test
的目錄結構:
/reporter
是生成測試報告的文件夾,這個在後面再說。
注意這個 /unit-test
文件夾,這個文件夾名字並非是固定的,只要你能把它和 karma.conf.js
中 files
的路徑名稱對應起來。
我們在 /unit-test
文件夾下創建 index.spec.js
文件,注意,以後此文件夾下所有的測試用例文件都應該以 **.spec.js
結尾,應該我們在 karma.conf.js
和 test-main.js
文件中都做了正則限制。
index.spec.js
文件內容如下:
var expect = chai.expect;
describe('unit test', function(){
it('dataHandle.cutLargeNum(1000) = 1.00萬',function(){
expect(dataHandle.cutLargeNum(10000)).to.equal('1.00萬');
})
})
chai
爲斷言庫,文中使用的是 BDD
風格的 expect
斷言。
我們在 gitbash
中輸入 $ karma start
運行測試,有以下輸出結果:
我們還可以修改 karma.conf.js
中的 singleRun
屬性爲 false
:
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
然後再運行 $ karma start
,此時你再修改 /static/js/common
下的任何一個 js 文件, karma
都會自動重新運行 /unit-test
下的測試用例。
8.生成測試報告
生成測試報告的模塊我選擇的是 karma-htmlfile-reporter
,相應需要做的配置我已經加在之前的 karma.conf.js
文件中了。
我們只需要執行 $ karma start --reporter html
,就可以發現 /test
目錄多了一個 /reporter
文件夾,裏面放着我們的測試報告 units.html
。
大概長這樣: