基于Karma和Jasmine的angular自动化单元测试

前言

在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:webangular-phonecat
app目录是存放主文件的。
test目录是存放单元测试文件的。
安装项目依赖的angular等包文件
D:webangular-phonecat>bower install
安装Karma
D:webangular-phonecat>npm install -g karma-cli
测试是否安装成功
D:webangular-phonecat>karma --version
Karma version: 0.12.24

3. Karma + Jasmine配置

拿第2个工程做示例。

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

D:webangular-phonecat>git checkout -f step-2
D:webangular-phonecat>cd test D:webangular-phonecat est>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:webangular-phonecat estkarma.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:webangular-phonecat	est>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:webangular-phonecat	est>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:workspacejavascriptkarma>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:UsersAdministratorAppDataLocalGoogleChromeApplicationchrome.exe
        Please set env variable CHROME_BIN

设置方法:找到系统中chrome的安装位置,找到chrome.exe文件


~ D:workspacejavascriptkarma>set CHROME_BIN="C:Program Files (x86)GoogleChromeApplicationchrome.exe"

转载请注明出处:

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

原文地址:https://www.cnblogs.com/shiqudou/p/4077071.html