2016-09-20 3 views
0

테스트 할 기능이있는 서비스가 있습니다. 그러나, 그 서비스의 각 기능 내부에서 사용되는 서비스 기능을 조롱하는 방법에 대해서는 잘 모릅니다. 올바른 URL이 호출되는지 확인하고 싶습니다. 내 테스트 스위트의 조각 지금Jasmine : GET 요청에서 올바른 URL이 호출되었는지 테스트하는 방법

angular.module("myModule").service('myService', MyService); 

MyService.$inject = ['$http']; 

function MyService($http) { 
    var myService = this; 

myService.request = function (reqType, url, headers, requestBody, fnc, fncFail) { 
     $http(createRequest(reqType, point, headers, requestBody)).then(function (response) { 
      if (typeof fnc == 'function') { 
       fnc(response.data); 
      } 
     }, function (response) { 
      if (typeof fncFail == 'function') { 
       fncFail(response);     
      } 
     }); 
    }; 

myService.getInfo = function (id, fnc, fncFail) {    
     myService.request("GET", "myURL", {"Accept":"application/json"}, null, function (data) { 
      fnc(data); 
     }, fncFail); 
}; 

:

beforeEach(inject(function ($injector) { 
    service = $injector.get("myService"); 
    httpBackend = $injector.get("$httpBackend"); 
    http = $injector.get("$http");  
})); 

it("function getInfo is called with the correct URL", function() { 
    spyOn(http, 'get').and.callThrough(); 
    myService.getInfo(id, fnc, fncFail); 
    expect(http.get).toHaveBeenCalledWith("myurl"); 
    httpBackend.flush(); 
}); 

이 올바른 접근 방식은 내 방법 "된 getInfo"을 테스트하는 경우 나, 확실하지 않다 때문에 여기

내 서비스 다른 서비스 기능 ("요청")을 호출합니다.

답변

2

$httpBackend을 사용하면 XHR 호출을 기대할 수 있습니다. 다음 afterEach 블록으로 호출이 이루어지지 않으면 테스트가 실패합니다.

afterEach(function() { 
    httpBackend.verifyNoOutstandingExpectation(); 
    httpBackend.verifyNoOutstandingRequest(); 
});  

it("function getInfo is called with the correct URL", function() { 
    httpBackend.expect('GET', "myurl").respond(200, {mocked: "response"}); 
    myService.getInfo(id, fnc, fncFail); 
    httpBackend.flush(); 
}); 
+0

정말 고마워요! 그것은 작동했습니다 :) – YourReflection

+0

안녕하세요 다시, 나는 여전히 문제가 실제로 내 예제에서 하나와 같은 메서드를 테스트 할 때,'TypeError : 'null'생성자'fnc (데이터); 내 함수에서 myService.getInfo = function (id, fnc, fncFail) { myService.request ("GET", "myURL", { "Accept": "application/json"}, null, function (data) { fnc (데이터); }, fncFail); }; 어떤 아이디어입니까? – YourReflection

+0

은 테스트에서'fnc'가 정의되어 있습니까? – Amygdaloideum

관련 문제