我想測試我的服務是使用緩存的GET請求拋出錯誤。
簡單化了測試的版本:
var url = "/test";
var whenTestRequest = $httpBackend.when('GET', url);
whenTestRequest.respond(200, "r1");
$http({ url: url, method: 'GET', cache: true }).success(function (value) {
expect(value).toBe("r1");
});
$httpBackend.flush();
whenTestRequest.respond(200, "r2");
$http({ url: url, method: 'GET', cache: true }).success(function (value) {
expect(value).toBe("r1");
});
$httpBackend.flush();
我需要第二$httpBackend.flush()
使我的第二個success
函數被調用,而是flush
是第二次調用拋出:
Error: No pending request to flush !
所以我需要在try
/catch
中包裝flush
。這有效,但是有沒有正確的方法來處理這個問題?
另一種方法是切換到使用'$ httpBackend.expectGET()''而不是$ httpBackend.when()'。原因在於「期望」版本更爲嚴格,您可以測試只有一個HTTP請求。這種方法顯着改變你的測試。坦率地說,我從未在測試中使用「when」函數b/c,我想斷言HTTP請求是按照我預期的順序/數量進行的。 – 2014-09-25 05:53:30
這只是咬我一口......我們不能成爲第一個遇到這個問題的人,我們可以嗎? – 2015-03-03 23:06:07