我有麻煩測試數據輪詢在我的控制器如何使用Jasmine測試AngularJS上的數據輪詢?
控制器的邏輯是這樣的
$onInit() {
this.requestRootLocations();
this.startDataPolling();
}
private startDataPolling() {
this.stop = this.$interval(() =>
this.requestRootLocations()
, this.DATA_POLLING_INTERVAL);
}
private requestRootLocations() {
this.locationsService.requestRootElements().then(function (locationItem) {
...
this.entityList = (locationItem["locations"] instanceof Array) ? locationItem["locations"] : [];
}.bind(this), function() {
console.log("Error on loading locations data.");
});
}
更新: 在服務HTTP請求:
public requestRootElements() {
return this.$http.get(this.API + "locations").then((response) => response.data);
}
這工作正常像預期一樣。
測試用例看起來像這樣
it("should call http request on intervals", function() {
ctrl.$onInit();
$httpBackend.whenGET(api + "locations").respond(200, locationData);
// advance in time by 1 seconds
$interval.flush(1000);
$httpBackend.expectGET(api + "locations");
// after 1 seconds locations should be called once
$httpBackend.flush();
expect(ctrl.counts.length).toBe(4);
expect(ctrl.entities.length).toBe(6);
$interval.flush(dataPollingInterval);
$httpBackend.expectGET(api + "locations"); //does not work, why?
$httpBackend.flush();
// after the second call the data should be the same in this case
expect(ctrl.counts.length).toBe(4);
expect(ctrl.entities.length).toBe(6);
});
但在第二expectGET是錯誤
Error: Unsatisfied requests: GET /apiv1/locations
這些$ http請求在哪裏?發佈截斷的代碼片段不會有幫助。如果這發生在控制器中,請將其完整發布。如果這發生在服務中,請發佈控制器和服務。 – estus
謝謝,我已更新問題 – Juri
仍不確定爲什麼失敗。對於初學者來說,DATA_POLLING_INTERVAL不是1000。真正的問題是幾個單元混合成一個集成測試,並不是很有效。它引入了太多的移動部件,並沒有測試任何不能同時獨立測試的東西。看到答案。 – estus