AngularJS 单元测试(二)详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

AngularJS 单元测试(二)详解

MakingChoice   2020-05-15 我要评论

使用对象模拟注入

我们可以非常容易的使用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 单元测试的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们