2015-10-25 62 views
2

我目前正在嘗試使用Karma和Jasmine測試我寫的AngularJS服務。但是,我目前遇到了$httpBackend的問題,我無法繞過它。這裏是我的服務和測試:AngularJS服務測試(茉莉花/ Karma) - 錯誤:意外的請求:GET

服務:

export default angular.module("api:events", []) 
.factory("Events", ($http) => { 
    let api = "http://localhost:5000/api/"; 
    let Events = {}; 

    Events.query = (params) => { 
     return $http.get(`${api}/events`, {params: params}).then((res) => { 
      return res.data; 
     }); 
    }; 

    Events.get = (params) => { 
     return $http.get(`${api}/events/` + params.id).then((res) => { 
      return res.data; 
     }); 
    }; 

    return Events; 
}); 

測試:

describe("api:events",() => { 
    let EventsFactory, $scope, http; 

    beforeEach(module("app")); 

    beforeEach(inject((_Events_, $rootScope, $httpBackend) => { 
     EventsFactory = _Events_; 
     $scope = $rootScope.$new(); 
     http = $httpBackend; 
    })); 


    it("should return an object",() => { 
     let data = {}; 
     let url = "http://localhost:5000/api/events/:id"; 
     let response = { id: "12345" }; 

     http.whenGET(url).respond(200, response); 

     data = EventsFactory.get({ id: "1"}); 

     expect(data).not.toEqual("12345"); 

     http.flush(); 

     expect(data).toEqual("12345"); 

     http.verifyNoOutstandingExpectation(); 
     http.verifyNoOutstandingRequest(); 
    }); 
}); 

而且我收到(由於http.flush())錯誤:

Chrome 46.0.2490 (Mac OS X 10.10.5) api:events test FAILED 
    Error: Unexpected request: GET http://localhost:5000/api/events/1 
    No more request expected 

如果我日誌數據後data = EventsFactory.get({ id: "1"});我得到Object{$$state: Object{status: 0}}

我也試過打電話給我的服務像這樣類似的結果:

EventsFactory.get({ id: "1"}).then((result) => { 
    data = result; 
}); 

有什麼想法?

+2

我相信原因是URL給'whenXXX()'是文字,即':id'部分會在「期望」中按原樣使用。我相信轉到'url ='http:// localhost:5000/api/events/1''將會解決這個問題。 –

+0

Nikos,就是這樣!這非常令人沮喪。儘管感謝您的幫助!如果您可以將其作爲答案發布,我會標記您的答案。 –

回答

2

這裏的問題在於給予whenXXX()expectXXX()方法的網址必須是字面的。我們可以直觀地預計,帶參數的URL(例如問題代碼中的:id)可以工作,但事實並非如此。因此,要糾正錯誤,只需更換:

let url = "http://localhost:5000/api/events/:id"; 

有:

let url = "http://localhost:5000/api/events/1"; // `1` is the literal id 
1

查看documentationverifyNoOutstandingExpectation()verifyNoOutstandingRequest()

它說:

Verifies that all of the requests defined via the expect api were made.

的關鍵詞有 「期望API」。您沒有使用「期望」API,而是使用「when」API。在使用「when」API時,您不應該在測試結束時調用這兩種方法中的任何一種。

documentation描述了「expect」和「when」API之間的區別。

+0

這是有道理的。但是,即使我刪除了這兩行,我仍然遇到了同樣的錯誤。 –

相關問題