AngularJS单元测试
网上有很多单元测试的教程,比如如何安装jasmine和ngMock,大家可以搜一下。这里就不在说了。下面重点介绍一个单元测试的过程。
加载一个模块
AngularJS用module来包括应用不同的部分比如controllers,services, filters。为了测试不同的部分,我们需要一个不同模块的引用,并且加载它。Angularjs模块注入使用ngMock模块。ngMock模块能够注入服务service进入单元测试。
ngMock暴露出angular.mock.module方法,缩写是module。
准备
需要准备的就是一个简单的AngularJS启动模块。
如何实现
angular.mock.module方法被用在beforeEach方法中。这个module方法需要一个模块的名字或者另外一个字面量对象来替代,将会被注入。
1、使用一个字符串名字来代表模块
beforeEach(module('services.emcees'))
2、添加字面量对象
beforeEach(module('services.emcees',{ beatjunkies': { 'dj': 'Babu' }) })
3、现在可以在测试中使用beatjunkies引用检索解决的对象,返回{'dj': 'Babu'}
4、最后你也可以提供一个方法,提供一个rapper引用。
beforeEach(module('services.emcees'),{ beatjunkies': { 'dj': 'Babu' }) },function($provider){ $provider.value('rapper', 'madchild') })
写一个测试
例如这个例子,将要开始测试一个关于更改scope值来更新内容的指令。当scope上定义的一个noclick方法触发的时候这个值就会被分配。这需要在HTML上的按钮触发。
例如:
.directive('emcee',function(){ return{ restrict:'E', link:function(scope,element,attr){ scope.onClick=function(){ element.text('Step up ' + scope.emcee + '!') } } } })
具体做法
1、创建两个变量,一个用于scope(var scope),另一个用于element(var element)。
2、确定载入你的模块 beforeEach(module('cookbook'))
3、创建一个beforeEach方法用来注入必要的依赖,并且指定1中的变量来声明这些变量。包括创建一个新的scope对象和为scope指定emcee值。
beforeEach(inject(function($rootscope,$compile){ rootscope=$rootscope; scope=$rootscope.$new(); scope.emcee='Izzy Ice' }))
4、紧接3在beforeEach函数中加入创建指令的部分。
beforeEach(inject(function($rootscope,$compile){ rootscope=$rootscope; scope=$rootscope.$new(); scope.emcee='Izzy Ice'; element=angular.element('<emcee></emcee>'); $compile(element)(scope); }))
5、紧接着第三步在beforeEach中启动所有的watcher
scope.$digest();
6、需要创建一个新的spec来定义期望的结果是什么。
it('should assign scope emcee to element text when the onClick handler is called',function(){ })
新闻热点
疑难解答
图片精选