文章出處

 

原文:http://www.cnblogs.com/wushangjue/p/4539189.html

注意:本文中出現的資料鏈接、karma的插件安裝等,均可能需要翻$墻后才能正確執行。

 

Jasmine是一個Javascript的測試工具,在Karma上運行Jasmine可完成Javascript的自動化測試、生成覆蓋率報告等。本文不包含Jasmine的使用細節,這幾天我會寫一篇Jasmine的入門文章,有興趣的朋友到時候可以看一下。

 

安裝Node.JS(版本:v0.12.4, windows-64)

Karma是運行在Node.js之上的,因此我們首先要安裝Node.js。到 https://nodejs.org/download/ 下載你系統所需的NodeJS版本,我下載的是windows-64位的msi版。

下載之后,雙擊 node-v0.12.4-x64.msi 運行并安裝,這個就不贅述了, 不斷下一步即可, 當然最好將目錄改一下。

圖1(選擇安裝內容,默認即可):

 

 

安裝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插件

繼續輸入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的調用,安裝命令如下,其中-g表示全局參數,這樣今后可以非常方便的使用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(運行后如圖所示出現了一行INFO信息,并沒有其他提示和動作,因為此時我們沒有配置karma的啟動參數。后面會加入karma.conf.js,這樣karma就會自動啟動瀏覽器并執行測試用例了):

 

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

 

Karma+Jasmine配置

執行命令init命令進行配置:

karma init

 

圖10(所有默認配置問題):

 

 說明:

1. 測試框架:我們當然選jasmine

2. 是否添加Require.js插件

3. 選擇瀏覽器: 我們選Chrome

4. 測試文件路徑設置,文件可以使用通配符匹配,比如*.js匹配指定目錄下所有的js文件(實際操作中發現該路徑是karma.conf.js文件的相對路徑,詳見下面我給出的實際測試配置及說明)

5. 在測試文件路徑下,需要排除的文件

6. 是否允許Karma監測文件,yes表示當測試路徑下的文件變化時,Karma會自動測試

 

我在虛擬機上測試的例子:

圖11(TestFiles和NodeJS處于E盤根目錄下,karma.conf.js處于文件夾NodeJS的根目錄下):

 

以下是karma.conf.js的完整內容:

復制代碼
 1 // Karma configuration
 2 // Generated on Fri May 29 2015 19:30:26 GMT+0800 (中國標準時間)
 3 
 4 module.exports = function(config) {
 5   config.set({
 6 
 7     // base path that will be used to resolve all patterns (eg. files, exclude)
 8     basePath: '../TestFiles',
 9 
10 
11     // frameworks to use
12     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
13     frameworks: ['jasmine'],
14 
15 
16     // list of files / patterns to load in the browser
17     files: [
18       '*.js'
19     ],
20 
21 
22     // list of files to exclude
23     exclude: [
24     ],
25 
26 
27     // preprocess matching files before serving them to the browser
28     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
29     preprocessors: {
30     },
31 
32 
33     // test results reporter to use
34     // possible values: 'dots', 'progress'
35     // available reporters: https://npmjs.org/browse/keyword/karma-reporter
36     reporters: ['progress'],
37 
38 
39     // web server port
40     port: 9876,
41 
42 
43     // enable / disable colors in the output (reporters and logs)
44     colors: true,
45 
46 
47     // level of logging
48     // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
49     logLevel: config.LOG_INFO,
50 
51 
52     // enable / disable watching file and executing tests whenever any file changes
53     autoWatch: true,
54 
55 
56     // start these browsers
57     // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
58     browsers: ['Chrome'],
59 
60 
61     // Continuous Integration mode
62     // if true, Karma captures browsers, runs the tests and exits
63     singleRun: false
64   });
65 };
復制代碼

 

說明:

若所有測試文件均處于同一個目錄下,我們可以設置basePath(也是相對于karma.conf.js文件的相對路徑),然后指定files,此時files則為basePath目錄下的文件相對路徑;

當然你也可以不設置basePath,直接使用相對于karma.conf.js文件的文件相對路徑,如本例中,我們若保持basePath默認為空,則files配置應為:

files: [
      '../TestFiles/jasmineTest.js',
      '../TestFiles/test.js'
    ]

 

test.js內容:

function TT() {
    return "abc";
}

 

jasmineTest.js內容:

describe("A suite of basic functions", function () {
    it("test", function () {
        expect("abc").toEqual(TT());
    });
});

 

啟動Karma:

karma start karma.conf.js

由于這次加上了配置文件karma.conf.js,因此Karma會按照配置文件中指定的參數執行操作了,由于我們配置的是在Chrome中測試,因此Karma會自動啟動Chrome實例,并運行測試用例:

 

圖12(左側的Chrome是Karma自動啟動的,右側的Node.js command prompt窗口中,最后一行顯示了執行結果):

 

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

 

若此時,我們將jasmineTest.js中對于調用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將自動執行測試用例,由于本例測試用例未通過,因此在屏幕上打印出了錯誤信息,Chrome的Console窗口中的日志信息需要刷新debug.html后顯示。

圖14(Karma自動檢測到文件變化并自動重新執行了測試用例):

 

代碼覆蓋率

如果你還想查看測試的代碼覆蓋率,我們可以安裝karma-coverage插件,安裝命令為:

npm install karma-coverage

 

圖15(安裝karma-coverage的過程):

 

修改karma.conf.js,增加覆蓋率的配置:

圖16(主要是變動了以下三個配置節點,其他的配置內容不變):

復制代碼
 1     // preprocess matching files before serving them to the browser
 2     // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
 3     preprocessors: {
 4         '../TestFiles/test.js':'coverage'
 5     },
 6 
 7 
 8     // test results reporter to use
 9     // possible values: 'dots', 'progress'
10     // available reporters: https://npmjs.org/browse/keyword/karma-reporter
11     reporters: ['progress','coverage'],
12     
13     coverageReporter:{
14         type:'html',
15         dir:'../TestFiles/coverage/'
16     },
復制代碼

 

變動如下:

  • 在reporters中增加coverage
  • preprocessors中指定js文件
  • 添加coverageReporter節點,將覆蓋率報告類型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
  });
};

執行命令:

karma start karma.conf.js

 

圖17(執行命令后,在配置文件coverageReporter節點中指定的dir中,我們將找到生成的覆蓋率報告,karma-coverage還生成了一層子文件夾,對應于執行測試的瀏覽器+版本號+操作系統版本):

 

參考資料

Karma-runner:http://karma-runner.github.io/0.12/index.html

Karma-runner安裝步驟:https://karma-runner.github.io/0.12/intro/installation.html

Karma config file: http://karma-runner.github.io/0.8/config/configuration-file.html

Karma files:http://karma-runner.github.io/0.8/config/files.html

Karma和Jasmin自動化單元測試:http://blog.fens.me/nodejs-karma-jasmine/

AngularJS的UnitTest:https://docs.angularjs.org/guide/unit-testing

后記

與grunt結合 - grunt-karma

grunt的安裝不多敘述,相關介紹可看http://www.gruntjs.net/getting-started

安裝grunt-karma

npm install grunt-karma --save-dev

配置Gruntfile

將以下代碼加入到你項目中的Gruntfile中

grunt.loadNpmTasks("grunt-karma");
karma: {
  unit: {
    configFile: "karma.conf.js"
  }
}

更多的配置看這里:https://www.npmjs.com/package/grunt-karma

運行karma

grunt karma

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    大師兄 發表在 痞客邦 留言(0) 人氣()