2015-10-23 132 views
1

我发现几个职位的测试服务,说明此代码的方式来进行异步单元测试:AngularJS,摩卡,柴:有承诺

服务:

angular.module('miservices', []) 
.service('myAppServices', ['$http', 'httpcalls', function($http, httpcalls) { 
    this.getAccountType = function(){ 
     return httpcalls.doGet('http://localhost:3010/...').then(function(data){ 
      return data; 
     }, function(error){ 
      ... 
     }); 
    }; 
    ... 

测试:

describe('testing myAppServices', function(){ 

beforeEach(module('smsApp')); 
it('should handle names correctly', inject(function(myAppServices){ 
    myAppServices.getAccountType() 
    .then(function(data) { 
     expect(data).equal({...}); 
}); 
... 

我们使用的是AngularJS,Mocha,Chai,我们安装了Sinon。

测试永远不会到达.then部分,但为什么?

谢谢!

+1

这个问题不是承诺,而是$ http。你必须嘲笑请求,你不这样做。 – estus

+0

你的意思是httpBackend他们? – Ramon

+1

没错。如果doGet和getAccountType对实际的http响应没有任何影响,那么您可以跳过此规范,并为其他规范模拟getAccountType。 – estus

回答

0

如果您正在测试您的服务,我会建议模拟您的“httpcalls”服务(因为这是在此测试范围之外)。

嘲笑它你可以有几种方法,一种方法是有一个模拟模块,你只能用你的单元测试。然后

angular.module('miservices.mocks', []) 
.service('httpcalls', ['$q', function($q) { 
    this.returnGet = ''; 
    this.doGet = function(url) { 
      return $q.when(this.returnGet); 
     }; 
    }; 

而且你的单元测试将是这样的:

describe('testing myAppServices', function(){ 

beforeEach(function() { 
module('smsApp'); 
module('miservices.mocks'); 
}); 
it('should handle names correctly', inject(function(myAppServices, httpcalls){ 
    httpcalls.returnGet = 'return data'; 
    myAppServices.getAccountType() 
    .then(function(data) { 
     expect(data).equal('return data'); 
}); 
... 

因为我们插入后应用模块的模拟考试模块,httpcalls服务将由其模拟版本覆盖,使我们能够测试正常myAppServices没有进一步的依赖。

+0

感谢@pedromarce,我会试试看 – Ramon