2013-12-14 3 views
2

나는이 약속을 반환하고 내부적으로 다른 두 약속을 사용한다이 방법 : 두 개의 약속이 함수 내에서 호출되는 것처럼단위 테스트 약속

this.getLocation = function() { 
    var deferred = $q.defer(); 
    var that = this; 

    this.getCoords().then(function(coords) { 
     var result = {}; 
     result.coords = coords; 

     that.coordsToAddress(coords).success(function(address) { 

     result.address = address; 
     deferred.resolve(result); 

     }).error(function() { 
     deferred.reject('Unable to request coords to address'); 
     }); 
    }, function(reason) { 
     deferred.reject(reason); 
    }); 

    return deferred.promise; 
    }; 

다른 모듈에 속하고 자신이 자신의 테스트, 난 그저 this.getCoords()this.coordsToAddress()이 호출되었는지 테스트하고 싶습니다. 마지막 하나가 실패하면서,

describe('getLocation()', function() { 

    beforeEach(function() { 
     Googlemaps.getLocation(); 
    }); 

    it('should call getCoords()', function() { 
     expect(Googlemaps.getCoords).toHaveBeenCalled(); 
    }); 

    it('should call coordsToAddress()', function() { 
     expect(Googlemaps.coordsToAddress).toHaveBeenCalled(); 
    }); 

    }); 

첫 번째 성공 :이 테스트를

spyOn(Googlemaps, 'getCoords').andCallThrough(); 
spyOn(Googlemaps, 'coordsToAddress').andCallThrough(); 

그리고 쓴 :

내가 설정 내 스파이를했습니다

Expected spy coordsToAddress to have been called. 

내 생각을 coordsToAddress()을 호출하려면 getCoords() 약속을 전액 채워야합니다. 어떻게해야합니까? coordsToAddress()이 호출되었는지 확인하기 전에 $rootScope.$spply()으로 다이제스트를 실행 해 보았습니다.

+0

나는 정확한 답변을 드릴 수 없으므로 전화를 사용하고 있습니다. 그러나 andCallThrough() 대신 getCoords() 스파이에 andCallFake()를 사용하면 가짜 함수 (작성한)가 다음에 해결할 수있는 약속을 되돌릴 수 있습니다. –

답변

3

정말 여기에서 수행하려고하는 작업에 따라 다릅니다. 비동기 호출을 실제로해야하는 경우 Jasmine and async에 대해 자세히 조사해야합니다.

함수가 호출되고 있는지 확인하려면 .andReturn을 사용하여 비동기 호출을 조롱하여 비동기 호출을 방지 할 수 있습니다. 이것은 어떤 메이크업에 어떤 아약스 호출을 허용하고 당신의 전화가 제대로 작동하는지 확인합니다

var coord = $q.defer().promise; 
spyOn(Googlemaps, 'getCoords').andReturn(coord.resolve(yourMockCoords)); 

var toAdd = $q.defer().promise; 
spyOn(Googlemaps, 'coordsToAddress').andReturn(toAdd.resolve(yourAddress)); 

:

그래서 조롱은 다음과 같이 될 것이다.