標(biāo)簽:前端開發(fā) 單元測(cè)試 jasmine
1. 什么是Jasmine
Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.This guide is running against Jasmine version 2.4.1.
簡(jiǎn)而言之依沮,Jasmine就是一個(gè)行動(dòng)驅(qū)動(dòng)開發(fā)模式的JS的單元測(cè)試工具抑诸。
Jasmine github主頁
官網(wǎng)教程: 英文提针,簡(jiǎn)單明了,自帶demo,強(qiáng)烈推薦學(xué)習(xí)
Jasmine下載: 里面有一個(gè)自帶的例子,SpecRunner.html, 打開就知道jasmine的大致使用了。
2. 基本使用
跟Qunit差不錯(cuò),首先要有一個(gè)模板接收測(cè)試結(jié)果。
當(dāng)然也可以配合自動(dòng)化工具坡疼,例如grunt,直接顯示在控制臺(tái)衣陶。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine v2.4.1</title>
<!-- jasmine運(yùn)行需要的文件 -->
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.4.1/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.4.1/jasmine.css">
<script src="lib/jasmine-2.4.1/jasmine.js"></script>
<script src="lib/jasmine-2.4.1/jasmine-html.js"></script>
<script src="lib/jasmine-2.4.1/boot.js"></script>
<!-- 要測(cè)試的代碼 -->
<script src="src/SourceForTest.js"></script>
<!-- 測(cè)試用例 -->
<script src="spec/TestCases.js"></script>
</head>
<body>
</body>
</html>
測(cè)試用例如下
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
expect(false).not.toBe(true);
//fail("test will fail if this code excute"); //可用于不想被執(zhí)行的函數(shù)中
});
});
describe
定義一組測(cè)試柄瑰,可嵌套;
it
定義其中一個(gè)測(cè)試剪况;
注意:應(yīng)該按BDD的模式來寫describe與it的描述教沾。
關(guān)于BDD可參考:說起B(yǎng)DD,你會(huì)想到什么译断?
expect()
的參數(shù)是需要測(cè)試的東西授翻,toBe()
是一種斷言,相當(dāng)于===
,not
相當(dāng)于取非孙咪。
jasmine還有更多的斷言堪唐,并且支持自定義斷言,詳細(xì)可見官網(wǎng)教程翎蹈。
3. SetUp與TearDown
在jasmine中用beforeEach
,afterEach
,beforeAll
,afterAll
來表示
describe("A spec using beforeEach and afterEach", function() {
var foo = 0;
beforeEach(function() {
foo += 1;
});
afterEach(function() {
foo = 0;
});
it("is just a function, so it can contain any code", function() {
expect(foo).toEqual(1);
});
it("can have more than one expectation", function() {
expect(foo).toEqual(1);
expect(true).toEqual(true);
});
});
4. 自定義斷言(matcher)
beforeEach(function(){
jasmine.addMatchers({
toBeSomeThing: function(){ //定義斷言的名字
return {
compare: function (actual, expected) { //compare是必須的
var foo = actual;
return {
pass: foo === expected || 'something' ,
message: "error message here" //斷言為false時(shí)的信息
} //要返回一個(gè)帶pass屬性的對(duì)象淮菠,pass就是需要返回的布爾值
//negativeCompare: function(actual, expected){ ... } //自定義not.的用法
}
};
}
});
});
5. this的用法
每進(jìn)行一個(gè)it
測(cè)試前,this
都會(huì)指向一個(gè)空的對(duì)象荤堪『狭辏可以利用這一點(diǎn)來共享變量,而不用擔(dān)心變量被修改
describe("A spec", function() {
beforeEach(function() {
this.foo = 0;
});
it("can use the `this` to share state", function() {
expect(this.foo).toEqual(0);
this.bar = "test pollution?";
});
it("prevents test pollution by having an empty `this` created for the next spec", function() {
expect(this.foo).toEqual(0);
expect(this.bar).toBe(undefined); //true
});
});
6. 閑置測(cè)試
在describe
和it
前加一個(gè)x
逞力,變成xdescribe
,xit
,就可以閑置該測(cè)試曙寡,這樣運(yùn)行時(shí)就不會(huì)自動(dòng)測(cè)試,需要手動(dòng)開始寇荧。
7. Spy
功能強(qiáng)大的函數(shù)監(jiān)聽器,可以監(jiān)聽函數(shù)的調(diào)用次數(shù)执隧,傳參等等揩抡,甚至可以偽造返回值户侥,詳細(xì)可參考官網(wǎng)教程
describe("A spy", function() {
var foo, bar = null;
beforeEach(function() {
foo = { setBar:function(value){bar = value;} };
spyOn(foo, 'setBar'); //關(guān)鍵,設(shè)定要監(jiān)聽的對(duì)象的方法
foo.setBar(123);
foo.setBar(456, 'another param');
});
it("tracks that the spy was called", function() {
expect(foo.setBar).toHaveBeenCalled();
});
it("tracks that the spy was called x times", function() {
expect(foo.setBar).toHaveBeenCalledTimes(2);
});
it("tracks all the arguments of its calls", function() {
expect(foo.setBar).toHaveBeenCalledWith(123);
expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
});
it("stops all execution on a function", function() {
expect(bar).toBeNull();
});
});
8. 創(chuàng)建spy
當(dāng)沒有函數(shù)需要監(jiān)聽時(shí)峦嗤,也可以創(chuàng)建一個(gè)spy對(duì)象來方便測(cè)試蕊唐。
describe("A spy, when created manually", function() {
var whatAmI;
beforeEach(function() {
whatAmI = jasmine.createSpy('whatAmI'); //創(chuàng)建spy對(duì)象,id='whatAmI'
whatAmI("I", "am", "a", "spy"); //可以當(dāng)作函數(shù)一樣傳入?yún)?shù)
});
it("is named, which helps in error reporting", function() {
expect(whatAmI.and.identity()).toEqual('whatAmI');
});
it("tracks that the spy was called", function() {
expect(whatAmI).toHaveBeenCalled();
});
it("tracks its number of calls", function() {
expect(whatAmI.calls.count()).toEqual(1);
});
it("tracks all the arguments of its calls", function() {
expect(whatAmI).toHaveBeenCalledWith("I", "am", "a", "spy");
});
it("allows access to the most recent call", function() {
expect(whatAmI.calls.mostRecent().args[0]).toEqual("I");
});
});
9. 定時(shí)任務(wù)測(cè)試
jasmine可以模仿js的定時(shí)任務(wù)setTimeOut
,setInterval
,并可以通過tick()
來控制時(shí)間烁设,方便定時(shí)任務(wù)的測(cè)試
beforeEach(function() {
timerCallback = jasmine.createSpy("timerCallback");
jasmine.clock().install(); //關(guān)鍵
});
afterEach(function() {
jasmine.clock().uninstall(); //關(guān)鍵
});
it("causes a timeout to be called synchronously", function() {
setTimeout(function() {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.clock().tick(101); //關(guān)鍵替梨,控制時(shí)間進(jìn)度
expect(timerCallback).toHaveBeenCalled();
});
it("causes an interval to be called synchronously", function() {
setInterval(function() {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.clock().tick(101);
expect(timerCallback.calls.count()).toEqual(1);
jasmine.clock().tick(50);
expect(timerCallback.calls.count()).toEqual(1);
jasmine.clock().tick(50);
expect(timerCallback.calls.count()).toEqual(2);
});
10. 異步測(cè)試
傳入done參數(shù)表示執(zhí)行異步測(cè)試,在beforeEach
調(diào)用done()
表示測(cè)試的開始装黑,再次調(diào)用done()
表示測(cè)試結(jié)束副瀑,否則測(cè)試不會(huì)結(jié)束
describe("Asynchronous specs", function() {
var value;
beforeEach(function(done) { //傳入done參數(shù)表示執(zhí)行異步測(cè)試
setTimeout(function() {
value = 0;
done();
}, 1);
});
it("should support async execution of test preparation and expectations", function(done) {
value++;
expect(value).toBeGreaterThan(0);
done();
});
describe("long asynchronous specs", function() {
beforeEach(function(done) {
done();
}, 1000); //beforeEach的第二個(gè)參數(shù)表示延遲執(zhí)行?
it("takes a long time", function(done) {
setTimeout(function() {
done();
}, 9000);
}, 10000); //jasmine默認(rèn)等待時(shí)間是5s恋谭,超出這個(gè)時(shí)間就認(rèn)為fail糠睡,可以在it的第二個(gè)參數(shù)設(shè)置等待時(shí)
//jasmine.DEFAULT_TIMEOUT_INTERVAL 可以設(shè)置全局的等待時(shí)間
afterEach(function(done) {
done();
}, 1000);
});
describe("A spec using done.fail", function() {
var foo = function(x, callBack1, callBack2) {
if (x) {
setTimeout(callBack1, 0);
} else {
setTimeout(callBack2, 0);
}
};
it("should not call the second callBack", function(done) {
foo(true,
done,
function() {
done.fail("Second callback has been called"); //可以用done.fail()來實(shí)現(xiàn)結(jié)束測(cè)試,但fail的情況
}
);
});
});
});
11. jasmine配合karma 與 grunt使用
用法就在jasmine搭在karma上實(shí)現(xiàn)自動(dòng)化疚颊,再搭在grunt上實(shí)現(xiàn)與其他插件集成狈孔,方便管理。不過jasmine也可以直接搭在grunt上材义,所以我不太懂為什么要多個(gè)karma均抽? anyway大家都在用,那么就學(xué)一下吧其掂。
如果后面執(zhí)行命令出錯(cuò)油挥,試下?lián)Q個(gè)控制臺(tái)
karma文檔
首先npm init
生成package.json
然后安裝karma,去到相應(yīng)的文件夾清寇,命令行中輸入
1 npm install -g karma-cli
只有這個(gè)全局安裝
2 npm install karma --save-dev
3 npm install karma-chrome-launcher --save-dev
用什么瀏覽器就裝什么
4 npm install karma-jasmine --save-dev
5 npm install jasmine-core --save-dev
上面那條命令裝不了jasmine-core喘漏,這里補(bǔ)上
然后karma init
生成karma.conf.js,過程類似生成package.json华烟,全部默認(rèn)即可翩迈,然后手動(dòng)更改。
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: [
'*.js'
],
// list of files to exclude
exclude: [
'karma.conf.js',
'gruntfile.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src.js':'coverage' //預(yù)處理盔夜,檢查測(cè)試覆蓋率
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
coverageReporter:{ //用于檢查測(cè)試的覆蓋率负饲,生成的報(bào)告在./coverage/index.html中
type:'html',
dir:'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_ERROR,
// 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: ['Firefox'],
// 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,
captureTimeout: 5000, //連接瀏覽器的超時(shí)
})
}
karma start karma.conf.js
就可以自動(dòng)運(yùn)行測(cè)試了,并且檢測(cè)文件的變化喂链。
注意:如果瀏覽器不是默認(rèn)安裝的路徑需要設(shè)置路徑到環(huán)境變量.
cmd: set FIREFOX_BIN = d:\your\path\firefox.exe
$ export CHROME_BIN = d:\your\path\chrome.exe
好像只在當(dāng)前控制臺(tái)窗口生效
可以參考該文 Karma和Jasmine自動(dòng)化單元測(cè)試
然后就是搭在grunt上
npm install grunt
npm install grunt-karma
npm install grunt-contrib-watch
配置gruntfile.js
module.exports = function(grunt){
grunt.initConfig({
pkg:grunt.file.readJSON('package.json'),
karma:{
unit:{
configFile:'karma.conf.js',
//下面覆蓋karma.conf.js的設(shè)置
background: true, //后臺(tái)運(yùn)行
singleRun: false, //持續(xù)運(yùn)行
}
},
watch:{
karma:{
files:['*.js'],
tasks:['karma:unit:run']
}
}
});
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask('default',['karma','watch']);
}
命令行直接輸入grunt
就可以彈出瀏覽器自動(dòng)監(jiān)聽和測(cè)試了返十,
不知道為什么第一次運(yùn)行時(shí)不能測(cè)試,要修改了源碼才會(huì)開始測(cè)試椭微。
更多可看見grunt-kamra官方文檔
結(jié)語
搬運(yùn)了官網(wǎng)的教程洞坑,有很多地方?jīng)]說清楚,jasmine還有更多更強(qiáng)大的功能蝇率,詳細(xì)還是要參考官網(wǎng)教程