jasmine - javascript的單元測試框架
2011/03/06

jasmine是一個有名的javascript單元測試框架,它是獨立的「行為驅動開發」框架,提供了對javascript開發者來說相對容易使用的測試語法,可以幫助你輕鬆寫出自己的單元測試代碼。
WIKI: https://github.com/pivotal/jasmine/wiki
API: http://pivotal.github.com/jasmine/jsdoc/index.html
(Jasmine的API文件是用jsdoc生成的,關於jsdoc)
可以在下載頁面直接下載jasmine的源碼:https://github.com/pivotal/jasmine
還可以使用git下載(關於git的用法,可以看這裡http://progit.org/book/zh/ch1-4.html)
|
1
|
$ git clone https:\/\/github.com/pivotal/jasmine.git |
下載jasmine的源碼之後,可以看到目錄有一個example的文件夾,這裡就是我們要說的例子
還有一個文件夾lib,這裡放了運行測試案例所必須的文件
其中jasmine.js就是整個框架的核心代碼,
jasmine-html.js用來展示測試結果,jasmine.css用來美化測試結果。
spec/: 包含了就是這個測試案例所有的測試規則
src/: 存放了我們需要測試的js文件對象
SpecRunner.html: 運行測試用例的環境
spec文件夾下的幾個文件,PlayerSpec.js就是針對src文件夾下的Player.js所寫的測試用例。
|
1
2
3
4
5
6
7
8
|
//it用於描述一條簡單的規則,其中第一個參數為實例的名稱//一般需要使用有實際判定式的有意義的語句來描述//第二個參數為測試需要執行的代碼it('should increment a variable', function () { var foo = 0;// set up the world foo++;// call your application code expect(foo).toEqual(1); // passes because foo == 1}); |
jasmine有一些自帶的規則
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
//compares objects or primitives x and y and passes if they are equivalentexpect(x).toEqual(y);//compares objects or primitives x and y and passes if they are the same objectexpect(x).toBe(y); //compares x to string or regular expression pattern and passes if they matchexpect(x).toMatch(pattern); // passes if x is not undefinedexpect(x).toBeDefined();//passes if x is nullexpect(x).toBeNull(); //passes if x evaluates to trueexpect(x).toBeTruthy();//passes if x evaluates to falseexpect(x).toBeFalsy(); //passes if array or string x contains yexpect(x).toContain(y); //passes if x is less than yexpect(x).toBeLessThan(y);//passes if x is greater than yexpect(x).toBeGreaterThan(y); passes if function fn throws exception e when executedexpect(fn).toThrow(e); |
如果以上規則不能滿足你的需求,你還以為自定義規則
|
1
2
3
4
5
6
7
8
9
10
11
|
beforeEach(function() { this.addMatchers({ //這裡就是自己定義的規則 toBePlaying: function(expectedSong) { //運行校驗代碼,最終返回boolean值 var player = this.actual; return player.currentlyPlayingSong === expectedSong && player.isPlaying; } });}); |