AngularJS 单元测试(二)详解
使用对象模拟注入
我们可以非常容易的使用angularjs的$provider服务用一个对象模拟一个依赖并且注入。
例子如下
angular.module('artists',[]). factory('Artists',['imageStore',function(imageStore){ return { thumb:function(){ return imageStore.thumbnailUrl(id) } } }])
如何实现
如何确定了服务
1、创建一个URL的引用,稍后会被mock捕获,和为Artists注入的一个变量
var URL;
var Artists;
2、紧接着在beforeEach方法中使用$provide 服务注册模拟的factory服务。使用一个对象模拟thumbnailUrl方法。
beforeEach(module(function($provide){ $provide.value('imageStore',{ thumbnailUrl:function(id){ url='/thumb/'+id } }) })
3、使用$injector服务注入这个方法,返回这个Artists服务并且用刚才创建的的变量来声明,稍后可以使用到。
beforeEach(inject(function($inject){ Artists=$inject.get('Artists'); }))
4、调用Artists创建一个简单的测试
it('return the correct artist thumbnailUrl',function(){ Artists.thumb('1'); expect(url).toBe('/thumbs/1'); })
5、这里有一个完整的使用$provide模拟测试例子,这返回一个定义了thumbnailUrl方法,
describe('factory:artists',function(){ var url; var Artists; beforeEach(module('artist')); beforeEach(module(function($provide){ $provide.value('imageStore',{ thumbnailUrl: function (id) { url = '/thumbs/' + id; } }) })); beforeEach(inject(function($injector){ Artists=$injector.get('Artists') })) it('return the correct artist thumbnailUrl',function(){ Artists.thumb('1'); expect(url).toBe('/thumb/1') }) })
使用spec模拟注册实例
为了声明依赖注入的实例,下面声明一个例子,下面有两个服务,第二个服务被注入到了第一个里。
angular.module('hiphop',[]) .factory('deejays',['$rootscope','scratch',function($rootscope,scratch){ return{ originator: 'DJ Kool Herc', technique: scratch.technique() } }]) .factory('scratch',['$rootscope',function($rootscope){ return{ technique:function(){ return 'breakbeat'; } } }])
2、
describe('Service: deejays',function(){ beforeEach(module('hiphop')); var deejays; beforeEach(inject(function($injector){ deejays=$injector.get('deejays'); })) beforeEach(inject(function($provide) { $provide.value('scratch',jasmine.createSpyObj('scratch', ['technique'])); })); it('should return the correct originator',function(){ expect(deejays.originator).toBe('DJ Kool Herc'); }) })
以上就是对AngularJS 单元测试的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!
相关文章
Angular5整合富文本编辑器TinyMCE的方法(汉化+上传)
TinyMCE是一个轻量级的富文本编辑器,相对于CK编辑器更加精简,但必须满足绝大部分场景的需要。这篇文章主要介绍了Angular5整合富文本编辑器TinyMCE(汉化+上传)的相关知识,需要的朋友可以参考下2020-05-05详解在 Angular 项目中添加 clean-blog 模板
本篇文章主要介绍了详解在 Angular 项目中添加 clean-blog 模板,非常具有实用价值,需要的朋友可以参考下2017-07-07详解Angular 4.x NgTemplateOutlet
这篇文章主要介绍了详解Angular 4.x NgTemplateOutlet,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-05-05
最新评论