我目前有一个递归函数,可以轮询网页并重试非 200 响应:
app.service('PingService', function($q, $http, $timeout) {
var timer = null;
var deferred = $q.defer();
function ping() {
var url = 'http://www.google.com';
function successCallback() {
deferred.resolve();
}
function retry(accountName) {
timer = $timeout(ping, 2000);
}
$http.get(url).success(successCallback).error(retry);
}
return {
pingUrl: function() {
ping();
return defer.promise;
}
}
为了测试这个实现,我目前在 jasmine 中进行了以下测试:
it('should retry on non 200 response', function() {
$httpBackend.whenGET('http://www.google.com').respond(504);
PingService.pingUrl();
$httpBackend.flush();
$timeout.flush(4001);
$httpBackend.flush(2);
}
不幸的是,这没有通过,因为队列中似乎只有 1 个 http 请求,而不是我预期的耗时量的 2 个。
我是否可以使用使用 $timeout 的递归函数对一段时间内进行的 http 重试次数进行单元测试?
最佳答案
我不知道你想用那里的 $timeout.flush() 做什么?我会使用 jasmine 的内置时钟功能来计算所需的时间量。
关于javascript - 在 AngularJS 单元测试中断言递归 $timeout 中的 http 调用次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29059012/