標簽:前端開發(fā) 單元測試 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.
簡而言之,Jasmine就是一個行動驅(qū)動開發(fā)模式的JS的單元測試工具。
Jasmine github主頁
官網(wǎng)教程: 英文,簡單明了,自帶demo,強烈推薦學習
Jasmine下載: 里面有一個自帶的例子,SpecRunner.html, 打開就知道jasmine的大致使用了。
2. 基本使用
跟Qunit差不錯,首先要有一個模板接收測試結(jié)果。
當然也可以配合自動化工具,例如grunt,直接顯示在控制臺。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine v2.4.1</title>
<!-- jasmine運行需要的文件 -->
<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>
<!-- 要測試的代碼 -->
<script src="src/SourceForTest.js"></script>
<!-- 測試用例 -->
<script src="spec/TestCases.js"></script>
</head>
<body>
</body>
</html>
測試用例如下
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定義一組測試,可嵌套;
it定義其中一個測試;
注意:應該按BDD的模式來寫describe與it的描述。
關于BDD可參考:說起B(yǎng)DD,你會想到什么?
expect()的參數(shù)是需要測試的東西,toBe()是一種斷言,相當于===,not相當于取非。
jasmine還有更多的斷言,并且支持自定義斷言,詳細可見官網(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時的信息
} //要返回一個帶pass屬性的對象,pass就是需要返回的布爾值
//negativeCompare: function(actual, expected){ ... } //自定義not.的用法
}
};
}
});
});
5. this的用法
每進行一個it測試前,this都會指向一個空的對象??梢岳眠@一點來共享變量,而不用擔心變量被修改
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. 閑置測試
在describe和it前加一個x,變成xdescribe,xit,就可以閑置該測試,這樣運行時就不會自動測試,需要手動開始。
7. Spy
功能強大的函數(shù)監(jiān)聽器,可以監(jiān)聽函數(shù)的調(diào)用次數(shù),傳參等等,甚至可以偽造返回值,詳細可參考官網(wǎng)教程
describe("A spy", function() {
var foo, bar = null;
beforeEach(function() {
foo = { setBar:function(value){bar = value;} };
spyOn(foo, 'setBar'); //關鍵,設定要監(jiān)聽的對象的方法
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
當沒有函數(shù)需要監(jiān)聽時,也可以創(chuàng)建一個spy對象來方便測試。
describe("A spy, when created manually", function() {
var whatAmI;
beforeEach(function() {
whatAmI = jasmine.createSpy('whatAmI'); //創(chuàng)建spy對象,id='whatAmI'
whatAmI("I", "am", "a", "spy"); //可以當作函數(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. 定時任務測試
jasmine可以模仿js的定時任務setTimeOut,setInterval,并可以通過tick()來控制時間,方便定時任務的測試
beforeEach(function() {
timerCallback = jasmine.createSpy("timerCallback");
jasmine.clock().install(); //關鍵
});
afterEach(function() {
jasmine.clock().uninstall(); //關鍵
});
it("causes a timeout to be called synchronously", function() {
setTimeout(function() {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.clock().tick(101); //關鍵,控制時間進度
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. 異步測試
傳入done參數(shù)表示執(zhí)行異步測試,在beforeEach調(diào)用done()表示測試的開始,再次調(diào)用done()表示測試結(jié)束,否則測試不會結(jié)束
describe("Asynchronous specs", function() {
var value;
beforeEach(function(done) { //傳入done參數(shù)表示執(zhí)行異步測試
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的第二個參數(shù)表示延遲執(zhí)行?
it("takes a long time", function(done) {
setTimeout(function() {
done();
}, 9000);
}, 10000); //jasmine默認等待時間是5s,超出這個時間就認為fail,可以在it的第二個參數(shù)設置等待時
//jasmine.DEFAULT_TIMEOUT_INTERVAL 可以設置全局的等待時間
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()來實現(xiàn)結(jié)束測試,但fail的情況
}
);
});
});
});
11. jasmine配合karma 與 grunt使用
用法就在jasmine搭在karma上實現(xiàn)自動化,再搭在grunt上實現(xiàn)與其他插件集成,方便管理。不過jasmine也可以直接搭在grunt上,所以我不太懂為什么要多個karma? anyway大家都在用,那么就學一下吧。
如果后面執(zhí)行命令出錯,試下?lián)Q個控制臺
karma文檔
首先npm init生成package.json
然后安裝karma,去到相應的文件夾,命令行中輸入
1 npm install -g karma-cli 只有這個全局安裝
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,這里補上
然后karma init生成karma.conf.js,過程類似生成package.json,全部默認即可,然后手動更改。
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' //預處理,檢查測試覆蓋率
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
coverageReporter:{ //用于檢查測試的覆蓋率,生成的報告在./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, //連接瀏覽器的超時
})
}
karma start karma.conf.js 就可以自動運行測試了,并且檢測文件的變化。
注意:如果瀏覽器不是默認安裝的路徑需要設置路徑到環(huán)境變量.
cmd: set FIREFOX_BIN = d:\your\path\firefox.exe
$ export CHROME_BIN = d:\your\path\chrome.exe
好像只在當前控制臺窗口生效
可以參考該文 Karma和Jasmine自動化單元測試
然后就是搭在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的設置
background: true, //后臺運行
singleRun: false, //持續(xù)運行
}
},
watch:{
karma:{
files:['*.js'],
tasks:['karma:unit:run']
}
}
});
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask('default',['karma','watch']);
}
命令行直接輸入grunt就可以彈出瀏覽器自動監(jiān)聽和測試了,
不知道為什么第一次運行時不能測試,要修改了源碼才會開始測試。
更多可看見grunt-kamra官方文檔
結(jié)語
搬運了官網(wǎng)的教程,有很多地方?jīng)]說清楚,jasmine還有更多更強大的功能,詳細還是要參考官網(wǎng)教程