基於Karma和Jasmine的angular自動化單元測試

前言javascript

在Java領域,Apache, Spring, JBoss 三大社區的開源庫,一應俱全,但每一個庫都在其領域中都鶴立雞羣。而Nodejs中各類各樣的開源庫,卻讓人眼花繚亂,不知從何下手。html

Nodejs領域: Jasmine作單元測試Karma自動化完成單元測試Grunt啓動Karma統一項目管理Yeoman最後封裝成一個項目原型模板,npm作nodejs的包依賴管理,bower作javascript的包依賴管理java

Java領域:JUnit作單元測試, Maven自動化單元測試,統一項目管理,構建項目原型模板,包依賴管理。node

Nodejs讓組合變得更豐富,卻又在加劇咱們的學習門檻。git

上面寫的有點遠了,回到文章的主題,Jasmine+Karma自動化單元測試。github

目錄web

  1. Karma的介紹
  2. Karma的安裝
  3. Karma + Jasmine配置
  4. 自動化單元測試
  5. Karma和istanbul代碼覆蓋率
  6. Karma第一次啓動時出現的問題

1. Karma的介紹

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

Karma是一個基於Node.js的JavaScript測試執行過程管理工具(Test Runner)。該工具可用於測試全部主流Web瀏覽器,也可集成到CI(Continuous integration)工具,也可和其餘代碼編輯器一塊兒使用。這個測試工具的一個強大特性就是,它能夠監控(Watch)文件的變化,而後自行執行,經過console.log顯示測試結果。npm

Jasmine是單元測試框架,本單將介紹用Karma讓Jasmine測試自動化完成。Jasmine的介紹,請參考文章:jasmine行爲驅動,測試先行bootstrap

istanbul是一個單元測試代碼覆蓋率檢查工具,能夠很直觀地告訴咱們,單元測試對代碼的控制程度。

2. Karma的安裝

系統環境:

win7 64bit, node v0.10.5, npm 1.2.19
首先,安裝Git工具,而後用如下命令從Github複製以angular-seed爲基礎的phonecat項目:
git clone git://github.com/angular/angular-phonecat.git

解壓到D:\web\angular-phonecat
app目錄是存放主文件的。
test目錄是存放單元測試文件的。
安裝項目依賴的angular等包文件
D:\web\angular-phonecat>bower install
安裝Karma
D:\web\angular-phonecat>npm install -g karma-cli
測試是否安裝成功
D:\web\angular-phonecat>karma --version
Karma version: 0.12.24

3. Karma + Jasmine配置

拿第2個工程作示例。

初始化karma配置文件karma.conf.js

D:\web\angular-phonecat>git checkout -f step-2
D:\web\angular-phonecat>cd test D:\web\angular-phonecat\test>karma init Which testing framework do you want to use ? Press tab to list possible options. Enter to move to the next question. > jasmine Do you want to use Require.js ? This will add Require.js plugin. Press tab to list possible options. Enter to move to the next question. > yes Do you want to capture any browsers automatically ? Press tab to list possible options. Enter empty string to move to the next quest ion. > Chrome > What is the location of your source and test files ? You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js". Enter empty string to move to the next question. > Should any of the files included by the previous patterns be excluded ? You can use glob patterns, eg. "**/*.swp". Enter empty string to move to the next question. > Do you wanna generate a bootstrap file for RequireJS? This will generate test-main.js/coffee that configures RequireJS and starts the tests. > no Which files do you want to include with
<script> tag ? This should be a script that bootstraps your test by configuring Require.js and kicking __karma__.start(), probably your test-main.js file. Enter empty string to move to the next question. > Do you want Karma to watch all the files and run the tests on change ? Press tab to list possible options. > yes Config file generated at "D:\web\angular-phonecat\test\karma.conf.js".

 

4. 自動化單元測試

3步準備工做:

  • 1. 建立源文件:用於實現某種業務邏輯的文件,就是咱們平時寫的js腳本
  • 2. 建立測試文件:符合jasmineAPI的測試js腳本
  • 3. 修改karma.conf.js配置文件

1). 建立源文件:用於實現某種業務邏輯的文件,就是咱們平時寫的js腳本

controllers.js,在html中ng-repeat循環輸出phones

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function($scope) {
  $scope.phones = [
    {'name': 'Nexus S',
     'snippet': 'Fast just got faster with Nexus S.'},
    {'name': 'Motorola XOOM™ with Wi-Fi',
     'snippet': 'The Next, Next Generation tablet.'},
    {'name': 'MOTOROLA XOOM™',
     'snippet': 'The Next, Next Generation tablet.'}
  ];
});

2). 建立測試文件:符合jasmineAPI的測試js腳本

controllersSpec.js

describe('PhoneCat controllers', function() {

  describe('PhoneListCtrl', function(){

    beforeEach(module('phonecatApp'));

    it('should create "phones" model with 3 phones', inject(function($controller) {
      var scope = {},
          ctrl = $controller('PhoneListCtrl', {$scope:scope});

      expect(scope.phones.length).toBe(3);
    }));

  });
});

3). 修改karma.conf.js配置文件
咱們這裏須要修改:files和exclude變量

module.exports = function(config){
  config.set({
    basePath : '../',
    files : [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/js/**/*.js',
      'test/unit/**/*.js'
    ],
    autoWatch : true,
    frameworks: ['jasmine'],
    browsers : ['Chrome'],
    plugins : [
            'karma-chrome-launcher',
            'karma-jasmine'
            ],
    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }
  });
};

啓動karma

D:\web\angular-phonecat\test>karma start
INFO [karma]: Karma v0.12.24 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2031 (Windows 7)]: Connected on socket XwUVHF6Pm0tqa67igE3O wi
th id 65679142
Chrome 37.0.2031 (Windows 7): Executed 1 of 1 SUCCESS (0.013 secs / 0.011 secs)

瀏覽器自動打開

修改controllersSpec.js,保存後,會自動執行單元測試。

5. Karma和istanbul代碼覆蓋率

增長代碼覆蓋率檢查和報告,增長istanbul依賴

D:\web\angular-phonecat\test>npm install karma-coverage

修改karma.conf.js配置文件

plugins : [
            'karma-chrome-launcher',
            'karma-jasmine',
            'karma-coverage'
            ],
    reporters:['progress','coverage'],
    preprocessors:{'app/js/controllers.js':'coverage'},
    coverageReporter:{
     type:'html',
     dir:'coverage/'
    }

啓動karma start,在工程目錄下面找到index.html文件,coverage/chrome/index.html

打開後,咱們看到代碼測試覆蓋綠報告

 

覆蓋率是100%,說明咱們完整了測試了src.js的功能。

6. Karma第一次啓動時出現的問題

CHROME_BIN的環境變量問題

~ D:\workspace\javascript\karma>karma start karma.conf.js
INFO [karma]: Karma v0.10.2 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
ERROR [launcher]: Cannot start Chrome
        Can not find the binary C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chrome.exe
        Please set env variable CHROME_BIN

設置方法:找到系統中chrome的安裝位置,找到chrome.exe文件

~ D:\workspace\javascript\karma>set CHROME_BIN="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"

轉載請註明出處:

http://blog.fens.me/nodejs-karma-jasmine/

相關文章
相關標籤/搜索