2016-08-18 44 views
0

我試圖單元測試以下功能:單元測試的諾言 - 在角度JS

Service.test = function(id) { 
 
\t return this.getDetails(id).then(function (details){ 
 

 
\t   return "name"; \t  
 
\t }); 
 
    }; 
 

到目前爲止,我有我自己試了一下,做以下的事情:

describe(
 
    'TempServ', 
 
    \t function() { 
 
\t var TempSer, $httpBackend, $q, CapabilityService; 
 

 
    \t beforeEach(inject(function(_TempServ_, _$httpBackend_, _$q_, 
 
\t \t \t \t \t _CapabilityService_) { 
 
\t \t TempServ = _TempServ_; 
 
\t \t $q = _$q_; 
 
\t \t $httpBackend = _$httpBackend_; 
 
\t \t CapabilityService = _CapabilityService_; 
 
\t \t \t })); 
 

 
\t it(" should be in Pending state",function() { 
 
\t \t spyOn(TemplateService, 'getDetails').and.callThrough(); 
 
\t \t console.log(TemplateService.test()); 
 
\t \t \t \t \t \t 
 
\t }); 
 

 
    \t \t });

我想要一些可以模擬getDetails的東西,我可以返回我想要的東西,而不是真正返回的東西,測試函數完全可以自行工作。 只有getDetails被模擬!

回答

1

嘗試做這樣的事情

spyOn(TemplateService, 'getDetails').and.returnValue($q.when('mockDetails')); 
$rootScope.$digest(); 

這將允許你做一個測試類似如下:

it('should be in pending state', function(done) { 
    spyOn(TemplateService, 'getDetails').and.returnValue($q.when('mockDetails')); 


    TemplateService.test().then(function(result) { 
    expect(result).toBe('name'); // this could also be a value computed with "mockDetails" 
    done(); 
    }); 

    $rootScope.$digest(); 
}); 
+0

我想,它的工作!謝謝:) 如果我收到任何問題,我會爲您解決更多問題,好嗎? –

1
spyOn(TemplateService, 'getDetails').and.callThrough(); 

該行將在間諜環境下執行getDetails的實際實現。您可以使用類似

spyOn(TemplateService, 'getDetails').and.returnValue(true) 

代替。如果您想測試回調中發生的情況,通常需要通過$ scope手動觸發摘要循環更新。

+0

的returnValue工程:) –