2016-09-20 105 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:'空'不是'fnc(數據)的構造函數;''函數myService.getInfo = function(id,fnc,fncFail)myService.request(「GET」,「myURL」,{「Accept」:「application/json」},null,function(data){ fnc(data); },fncFail); };'有什麼想法? – YourReflection

+0

是否在您的測試中定義了「fnc」? – Amygdaloideum

相關問題