結合angularjs,Karma和Jasmine自動化單元測試

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   color   ar   os   使用   

前言

在Java領域,Apache, Spring, JBoss 三大社區的開源庫,包羅永珍,但每個庫都在其領域中都鶴立雞群。而Nodejs中各種各樣的開源庫,卻讓人眼花繚亂,不知從何下手。

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

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

Nodejs讓組合變得更豐富,卻又在加重我們的學習門檻。我還說不清楚,也看不透!

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

目錄

  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這種名字更讓人猜不透!

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

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

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配置

初始化karma設定檔karma.conf.js

D:\web\angular-phonecat>cd testD:\web\angular-phonecat\test>karma initWhich testing framework do you want to use ? Press tab to list possible options. Enter to move to the next question. > jasmineDo 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.> yesDo 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. > noWhich 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. > yesConfig 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 startINFO [karma]: Karma v0.12.24 server started at http://localhost:9876/INFO [launcher]: Starting browser ChromeINFO [Chrome 37.0.2031 (Windows 7)]: Connected on socket XwUVHF6Pm0tqa67igE3O with id 65679142Chrome 37.0.2031 (Windows 7): Executed 1 of 1 SUCCESS (0.013 secs / 0.011 secs)

瀏覽器自動開啟

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

 

結合angularjs,Karma和Jasmine自動化單元測試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.