Karma+Jasmine實現自動化單元測試


 

1.Karma介紹

Karma是Testacular的新名字,在2012年google開源了Testacular,2013年Testacular改名為Karma。Karma是一個讓人感到非常神秘的名字,表示佛教中的緣分,因果報應,比Cassandra這種名字更讓人猜不透!

 

Karma是一個基於Node.js的JavaScript測試執行過程管理工具(Test Runner)。該工具可用於測試所有主流Web瀏覽器,也可集成到CI(Continuous integration)工具,也可和其他代碼編輯器一起使用。這個測試工具的一個強大特性就是,它可以監控(Watch)文件的變化,然后自行執行,通過console.log顯示測試結果。


 

2.Jasmine介紹

Jasmine (茉莉)是一款 JavaScript BDD(行為驅動開發)測試框架,它不依賴於其他任何 JavaScript 組件。它有干凈清晰的語法,讓您可以很簡單的寫出測試代碼。對基於 JavaScript 的開發來說,它是一款不錯的測試框架選擇。


3.jasmine基礎語法

 
jasmine是一個行為驅動測試JavaScript代碼的框架。 它不依賴與任何其他JavaScript框架,也不是必須需要DOM。它有一個干凈的,明顯的語法,以便你可以輕松的寫測試。
 
1)Suites : 套件 (describe Your Tests)

Suite表示一個測試集,以函數describe(string, function)封裝,它包含2個參數:
string:測試組名稱,
function:測試組函數。

一個Suite(describe)包含多個Specs(it),一個Specs(it)包含多個斷言(expect)。

 

2)Specs : 規范

調用全局方法  it  來定義測試 規范 。它也有兩個參數, 一個字符串和一個方法。
(1)字符串是這個 規范 的名稱或者標題。
(2)方法就是這個 規范 或者測試。
一個 規范包含一個或者多個測試代碼狀態的期望值。
一個jasmine的期望值是一個true或者false的斷言。所有期望值都是true的規范才是合格的規范,有一個或者多個期望值是false的規范就是失敗的規范。
1 describe("A suite",function(){
2     it("contains spec with an expectation",function(){
3         expect(true).toBe(true);
4     });
5 });

 

3)方法

由於 describe 和 it 塊是函數,它們可以包含實現測試所必需的任何可執行代碼。JavaScript的作用域規則適用,所以在 describe 的套件里的任何 it 塊,變量聲明是有效的。
 

4)Expectations :期望值

期望值是用 except 方法來創建的,它需要一個值,稱為實際值。這是一個需要期望值的匹配方法鏈。
 
一個Suite(describe)包含多個Specs(it),一個Specs(it)包含多個斷言(expect)。
 

5)Matchers : 匹配器

每一個匹配器實現的是真實值和期望值的比較。它負責報告給jasmine如果期望值是真的或者假的。jasmine將使這個規范通過或者失敗。
在調用匹配器之前, 通過 使用 not 鏈接調用 except , 任何匹配器可以評估一個反的斷言。
1 it("and can have a negative case",function(){
2     expect(false).not.toBe(true);
3 });

 

 
jasmine包含豐富的匹配器。所有的期望值和規范通過都需要用到。
 
以下測試都是通過的。
 
(1)toBe() : 用來比較數字或者字符串是否相等,不支持對象的比較。
1 describe("Included matchers:",function(){
2     it("The 'toBe' matcher compares with ===",function(){
3         var a =12;
4         var b = a;
5         expect(a).toBe(b);
6         expect(a).not.toBe(null);
7     });
8 }    

 

 
(2)toEqual() :可以用來比較簡單的文本和變量,還有對象是否相等。
 
(3)toMatch():針對正則表達式。
1 it("The 'toMatch' matcher is for regular expressions",function(){
2     var message ='foo bar baz';
3     expect(message).toMatch(/bar/);
4     expect(message).toMatch('bar');
5     expect(message).not.toMatch(/quux/);
6 });

 

(4)toBeDefined():對未定義進行判斷,如果定義了則為true。
 
(5)toBeUndefined(): 對未定義進行判斷,如果沒有定義則為true。
 1 it("The 'toBeDefined' matcher compares against `undefined`",function(){
 2     var a ={
 3         foo:'foo'
 4     };
 5     expect(a.foo).toBeDefined();
 6     expect(a.bar).not.toBeDefined();
 7 });
 8 
 9 it("The `toBeUndefined` matcher compares against `undefined`",function(){
10     var a ={
11         foo:'foo'
12     };
13     expect(a.foo).not.toBeUndefined();
14     expect(a.bar).toBeUndefined();
15 });
16     

 

(6)toBeNull():對空進行比較
1 it("The 'toBeNull' matcher compares against null",function(){
2     var a =null;
3     var foo ='foo';
4     expect(null).toBeNull();
5     expect(a).toBeNull();
6     expect(foo).not.toBeNull();
7 });

 

 
(7)toBeTruthy():判斷布爾值,是布爾值則為true
 
(8)toBeFalsy(): 判斷布爾值,不是布爾值則為true
 
(9)toContain():判斷字符串或者數組中是否包含某個值,包含則為true。
 1 describe("The 'toContain' matcher",function(){
 2     it("works for finding an item in an Array",function(){
 3         var a =["foo","bar","baz"];
 4         expect(a).toContain("bar");
 5         expect(a).not.toContain("quux");
 6     });
 7     it("also works for finding a substring",function(){
 8         var a ="foo bar baz";
 9         expect(a).toContain("bar");
10         expect(a).not.toContain("quux");
11     });
12 });

 

 
(10)toBeLessThan():比較數值大小,若小於則為true。
 
(11)toBeGreaterThan(): 比較數值大小,若大於則為true。
 1 it("The 'toBeLessThan' matcher is for mathematical         comparisons",function(){
 2     var pi =3.1415926, e =2.78;
 3     expect(e).toBeLessThan(pi);
 4     expect(pi).not.toBeLessThan(e);
 5 });
 6 
 7 it("The 'toBeGreaterThan' is for mathematical comparisons",function(){
 8     var pi =3.1415926, e =2.78, c =3;
 9     expect(c).toBeGreaterThan(e);
10     expect(c).not.toBeGreaterThan(pi);
11 });

 

 
(12)toBeCloseTo():精密的數學比較
1 it("The 'toBeCloseTo' matcher is for precision math comparison",function(){
2     var pi =3.1415926, e =2.78;
3     expect(pi).not.toBeCloseTo(e,2);
4     expect(pi).toBeCloseTo(e,0);
5 });
 
(13)toThrow():拋出異常時為true
 1 it("The 'toThrow' matcher is for testing if a function throws an         exception",function(){
 2     var foo =function(){
 3         return1+2;
 4     };
 5     var bar =function(){
 6         return a +1;
 7     };
 8     expect(foo).not.toThrow();
 9     expect(bar).toThrow();
10 });

 

 

4.基本實現

 
1)環境安裝
使用npm安裝karma:
輸入: npm install -g karma  會在全局安裝karma, 但是目前還不能使用。
  注:npm install karma --save-dev  --save-dev的意思是只有在開發的時候用到這個npm包。但一般是使用上面的方式。
      此時項目沒有任何變化。
 
2)配置karma.config.js
輸入: karma init
一直回車,直到生成karma.config.js文件。
 1 // Karma configuration
 2 // Generated on Fri Oct 21 2016 12:00:54 GMT+0800 (中國標准時間)
 3 module.exports =function(config){
 4  config.set({
 5  // base path that will be used to resolve all patterns (eg. files, exclude)
 6   basePath:'',
 7 // frameworks to use
 8 // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
 9   frameworks:['jasmine'],
10 // list of files / patterns to load in the browser。!!!這個數組是用來存放被測試代碼和測試代碼的,默認為空!!!
11   files:[
12   ],
13 // list of files to exclude
14   exclude:[
15   ],
16 // preprocess matching files before serving them to the browser
17 // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
18   preprocessors:{
19   },
20 // test results reporter to use
21 // possible values: 'dots', 'progress'
22 // available reporters: https://npmjs.org/browse/keyword/karma-reporter
23   reporters:['progress'],
24 // web server port
25   port:9876,
26 // enable / disable colors in the output (reporters and logs)
27   colors:true,
28 // level of logging
29 // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
30   logLevel: config.LOG_INFO,
31 // enable / disable watching file and executing tests whenever any file changes
32   autoWatch:true,
33 // start these browsers
34 // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
35   browsers:['Chrome'],
36 // Continuous Integration mode
37 // if true, Karma captures browsers, runs the tests and exits
38   singleRun:false,
39 // Concurrency level
40 // how many browser should be started simultaneous
41   concurrency:Infinity
42   })
43 };

 

需要注意的是 karma 配置中的 singleRun 這個參數,設置為 false 的話,karma 會自動監控測試環境,默認是 Chrome, 如果你關掉了,karma 會自動重新啟動一個。如果配置為 true,執行一次測試之后,karma 會自動停掉。 autoWatch : true會自動執行測試用例

這兩個參數不需要修改,使用默認值就好。

 

karma 支持三個命令。

  • start [<configFile>] [<options>] 啟動 Karma 持續執行,也可以執行單次的測試,然后直接收集測試結果.
  • init [<configFile>] 初始化配置文件.
  • run [<options>] [ -- <clientArgs>] Trigger a test run. 
 
3)安裝集成包
輸入: npm install karma-jasmine

 

4)新建測試用例

在項目文件夾中,創建一個名為 test 的子文件夾來保存測試用例。然后在 test 文件夾中創建一個 unit 的文件夾來保存單元測試用例。一般來說,我們會為測試用例的文件名稱提供一個特定的模式,以便對測試用例進行統一處理,這里我們約定測試用例的文件名以 .spec.js 為結尾。

(1)自定義測試

1 describe('hello',function(){
2     it('test hello',function(){
3        var a ='hello';
4         expect(a).toEqual('hello');
5     });
6 });

 

(2)測試真實js文件
    add.js
1 function add(a,b){
2     return a + b;
3 }

 

   add.spec.js
 1 describe('hello',function(){
 2     it('test add',function(){
 3         var a = add(3,6);
 4         expect(a).toEqual(9);
 5     });
 6 
 7     it('test add',function(){
 8         var a = add(3,6);
 9         expect(a).toEqual(10);
10     });
11 });
 

5)修改karma配置文件

確認你的 karma 配置文件中,包含了被測試代碼和測試代碼。

// list of files / patterns to load in the browser
files: [
    'src/**/*.js',
'test/**/*.spec.js'
],
// list of files to exclude
exclude: [
    'karma.conf.js'
],

 

 
6)運行測試
輸入: karma start karma.conf.js
(直接輸入 karma start 也行)
 
報錯時:
 
另外,運行之后會生成頁面:
 

點擊 DEBUG 按鈕,可以進入實際的測試頁面。

這個頁面看起來是空白的,但是執行了實際的測試腳本,右擊鼠標點擊檢查,可以看到實際的內容:

 






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM