JavaScript測試工具之Karma-Jasmine的安裝和使用詳解
1.Karma介紹
Karma是Testacular的新名字,在2012年google開源了Testacular,2013年Testacular改名為Karma。Karma是一個讓人感到非常神秘的名字,表示佛教中的緣分,因果報應,比Cassandra這種名字更讓人猜不透!
Karma是一個基于Node.js的JavaScript測試執(zhí)行過程管理工具(Test Runner)。該工具可用于測試所有主流Web瀏覽器,也可集成到CI(Continuous integration)工具,也可和其他代碼編輯器一起使用。這個測試工具的一個強大特性就是,它可以監(jiān)控(Watch)文件的變化,然后自行執(zhí)行,通過console.log顯示測試結(jié)果。
2.Jasmine介紹
Jasmine (茉莉)是一款 JavaScript BDD(行為驅(qū)動開發(fā))測試框架,它不依賴于其他任何 JavaScript 組件。它有干凈清晰的語法,讓您可以很簡單的寫出測試代碼。對基于 JavaScript 的開發(fā)來說,它是一款不錯的測試框架選擇。
比較流行的有Qunit和Jasmine,如果你想更詳細了解二者的區(qū)別,請狠狠的點擊Javascript單元測試框架Qunit和Jasmine的比較。
腳本之家友情提醒大家需要注意點:本文中出現(xiàn)的資料鏈接、karma的插件安裝等,均可能需要翻$墻后才能正確執(zhí)行。
步驟一:安裝Node.JS(版本:v0.12.4, windows-64)
Karma是運行在Node.js之上的,因此我們首先要安裝Node.js。到 https://nodejs.org/download/ 下載你系統(tǒng)所需的NodeJS版本,我下載的是windows-64位的msi版。
下載之后,雙擊 node-v0.12.4-x64.msi 運行并安裝,這個就不贅述了, 不斷下一步即可, 當然最好將目錄改一下。
圖1(選擇安裝內(nèi)容,默認即可):

步驟二:安裝Karma
運行Node.js的命令行程序:Node.js command prompt:
圖2(處于“開始->所有程序->Node.js”中):

圖3(我們將安裝到E:\Karma路徑下):

輸入命令安裝Karma:
npm install karma --save-dev
圖4(Karma安裝完畢后):

步驟三:安裝karma-jasmine/karma-chrome-launcher插件
繼續(xù)輸入npm命令安裝karma-jasmine、karma-chrome-launcher插件:
npm install karma-jasmine karma-chrome-launcher --save-dev
圖5(karma-jasmine、karma-chrome-launcher安裝完畢之后):

步驟四:安裝karma-cli
karma-cli用來簡化karma的調(diào)用,安裝命令如下,其中-g表示全局參數(shù),這樣今后可以非常方便的使用karma了:
npm install -g karma-cli
圖6(karma-cli安裝完畢之后):

Karma-Jasmine安裝完畢:
圖7(安裝完畢后,在E:\Karma文件夾下會有一個node_modules目錄,里面包含剛才安裝的karma、karma-jasmine、karma-chrome-launcher目錄,當然還包含了jasmine-core目錄):
開啟Karma:
輸入命令:
karma start
圖8(運行后如圖所示出現(xiàn)了一行INFO信息,并沒有其他提示和動作,因為此時我們沒有配置karma的啟動參數(shù)。后面會加入karma.conf.js,這樣karma就會自動啟動瀏覽器并執(zhí)行測試用例了):

圖9(手動打開Chrome,輸入localhost:9876,如果看到這個頁面,證明已經(jīng)安裝成功):

Karma+Jasmine配置:
執(zhí)行命令init命令進行配置:
karma init
圖10(所有默認配置問題):

說明:
1. 測試框架:我們當然選jasmine
2. 是否添加Require.js插件
3. 選擇瀏覽器: 我們選Chrome
4. 測試文件路徑設置,文件可以使用通配符匹配,比如*.js匹配指定目錄下所有的js文件(實際操作中發(fā)現(xiàn)該路徑是karma.conf.js文件的相對路徑,詳見下面我給出的實際測試配置及說明)
5. 在測試文件路徑下,需要排除的文件
6. 是否允許Karma監(jiān)測文件,yes表示當測試路徑下的文件變化時,Karma會自動測試
我在虛擬機上測試的例子:
圖11(TestFiles和NodeJS處于E盤根目錄下,karma.conf.js處于文件夾NodeJS的根目錄下):

以下是karma.conf.js的完整內(nèi)容:
// Karma configuration
// Generated on Fri May :: GMT+ (中國標準時間)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '../TestFiles',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'*.js'
],
// list of files 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: ['progress'],
// web server port
port: ,
// 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
});
};
說明:
若所有測試文件均處于同一個目錄下,我們可以設置basePath(也是相對于karma.conf.js文件的相對路徑),然后指定files,此時files則為basePath目錄下的文件相對路徑;
當然你也可以不設置basePath,直接使用相對于karma.conf.js文件的文件相對路徑,如本例中,我們?nèi)舯3謆asePath默認為空,則files配置應為:
files: [
'../TestFiles/jasmineTest.js',
'../TestFiles/test.js'
]
test.js內(nèi)容:
function TT() {
return "abc";
}
jasmineTest.js內(nèi)容:
describe("A suite of basic functions", function () {
it("test", function () {
expect("abc").toEqual(TT());
});
});
啟動Karma:
karma start karma.conf.js
由于這次加上了配置文件karma.conf.js,因此Karma會按照配置文件中指定的參數(shù)執(zhí)行操作了,由于我們配置的是在Chrome中測試,因此Karma會自動啟動Chrome實例,并運行測試用例:
圖12(左側(cè)的Chrome是Karma自動啟動的,右側(cè)的Node.js command prompt窗口中,最后一行顯示了執(zhí)行結(jié)果):

圖13(如果我們點擊圖12中的debug按鈕,進入debug.html并按F12打開開發(fā)者工具,選擇Console窗口,我們將能看到jasmine的執(zhí)行日志):

若此時,我們將jasmineTest.js中對于調(diào)用TT方法的期望值改為"abcd"(實際為"abc"):
describe("A suite of basic functions", function () {
it("test", function () {
expect("abcd").toEqual(TT());
});
});
由于我們在karma.conf.js中設置了autoWatch為true:
autoWatch: true
Karma將自動執(zhí)行測試用例,由于本例測試用例未通過,因此在屏幕上打印出了錯誤信息,Chrome的Console窗口中的日志信息需要刷新debug.html后顯示。
圖14(Karma自動檢測到文件變化并自動重新執(zhí)行了測試用例):

代碼覆蓋率:
如果你還想查看測試的代碼覆蓋率,我們可以安裝karma-coverage插件,安裝命令為:
npm install karma-coverage
圖15(安裝karma-coverage的過程):

修改karma.conf.js,增加覆蓋率的配置:
圖16(主要是變動了以下三個配置節(jié)點,其他的配置內(nèi)容不變):
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'../TestFiles/test.js':'coverage'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','coverage'],
coverageReporter:{
type:'html',
dir:'../TestFiles/coverage/'
},
變動如下:
在reporters中增加coverage
preprocessors中指定js文件
添加coverageReporter節(jié)點,將覆蓋率報告類型type設置為html,輸入目錄dir指定到你希望的目錄中
此時完整的karma.conf.js如下:
// Karma configuration
// Generated on Fri May 29 2015 19:30:26 GMT+0800 (中國標準時間)
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: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../TestFiles/jasmineTest.js',
'../TestFiles/test.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'../TestFiles/test.js':'coverage'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','coverage'],
coverageReporter:{
type:'html',
dir:'../TestFiles/coverage/'
},
// 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
});
};
執(zhí)行命令:
karma start karma.conf.js
圖17(執(zhí)行命令后,在配置文件coverageReporter節(jié)點中指定的dir中,我們將找到生成的覆蓋率報告,karma-coverage還生成了一層子文件夾,對應于執(zhí)行測試的瀏覽器+版本號+操作系統(tǒng)版本):

相關文章
javascript 使用for循環(huán)時該注意的問題-附問題總結(jié)
所謂for循環(huán)就是重復的執(zhí)行一段代碼,for循環(huán)也是希望在創(chuàng)建循環(huán)時常會用到的工具,這篇內(nèi)容主要給大家介紹javascript 使用for循環(huán)時該注意的問題-附問題總結(jié),需要的朋友可以參考下2015-08-08
javascript設計模式 – 工廠模式原理與應用實例分析
這篇文章主要介紹了javascript設計模式 – 工廠模式,結(jié)合實例形式分析了javascript工廠模式基本概念、原理、定義、應用場景及相關操作注意事項,需要的朋友可以參考下2020-04-04
JavaScript及jquey實現(xiàn)多個數(shù)組的合并操作
這篇文章主要介紹了JavaScript及jquey實現(xiàn)多個數(shù)組的合并操作,在某些情況下還是比較實用的,需要的朋友可以參考下2014-09-09
Javascript 拖拽的一些簡單的應用(逐行分析代碼,讓你輕松了拖拽的原理)
這篇文章主要介紹了Javascript 拖拽的一些簡單的應用(逐行分析代碼,讓你輕松了拖拽的原理),需要的朋友可以參考下2015-01-01
借用Google的Javascript API Loader來加速你的網(wǎng)站
加速頁面加載速度有一個方法就是把CSS和JS文件放到另外一個單獨的服務器上,這樣在訪問量比較大的情況下可以分擔主服務器的壓力2009-01-01

