2015-10-23 133 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