博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基于Karma和Jasmine的angular自动化单元测试
阅读量:4571 次
发布时间:2019-06-08

本文共 5360 字,大约阅读时间需要 17 分钟。

前言

在Java领域,Apache, Spring, JBoss 三大社区的开源库,包罗万象,但每个库都在其领域中都鹤立鸡群。而Nodejs中各种各样的开源库,却让人眼花缭乱,不知从何下手。

Nodejs领域: ,,,,npm做nodejs的包依赖管理,。

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的介绍,请参考文章:

istanbul是一个单元测试代码覆盖率检查工具,可以很直观地告诉我们,单元测试对代码的控制程度。

2. Karma的安装

系统环境:

win7 64bit, node v0.10.5, npm 1.2.19 首先,安装工具,然后用以下命令从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 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 

 

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,保存后,会自动执行单元测试。

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.jsINFO [karma]: Karma v0.10.2 server started at http://localhost:9876/INFO [launcher]: Starting browser ChromeERROR [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"

转载请注明出处:

 

转载于:https://www.cnblogs.com/shiqudou/p/4077071.html

你可能感兴趣的文章
Django ORM 最后操作
查看>>
HDU 1050(贪心)
查看>>
java设计模式之代理模式
查看>>
spring心得2--bean的生命周期@Spring监听器的作用@Spring初始化容器案例分析@web项目使用...
查看>>
顺序栈
查看>>
Rsync详解
查看>>
【每日一读】Java编程中“为了性能”尽量要做到的一些地方
查看>>
什么是内网、什么是公网、什么是NAT
查看>>
【堆/排序】堆排序的两种建堆方法
查看>>
类的内置方法
查看>>
项目中使用的第三方开源库
查看>>
NOIP2009 潜伏者
查看>>
本地预览的vue项目,在githubpage静态展示
查看>>
SC命令---安装、开启、配置、关闭 cmd命令行和bat批处理操作windows服务
查看>>
Register Form Code
查看>>
iphone 如何清空UIWebView的缓存
查看>>
Java——变量
查看>>
定时关闭AWS上的EC2机器实例
查看>>
grep、awk、sed命令详解1
查看>>
Jenkins邮件配置
查看>>