在angularjs中为promise设置超时处理程序



我正试图在控制器中设置一个超时,这样,如果在250毫秒内没有收到响应,它就会失败。我已经将我的单元测试设置为超时10000,这样就应该满足这个条件,有人能给我指明正确的方向吗?(编辑:我试图在不使用$http服务的情况下实现这一点,我知道它提供了超时功能)

(EDIT-我的其他单元测试都失败了,因为我没有对它们调用timeout.flush,现在我只需要在promiseService.getPromise()返回未定义的promise时收到超时消息。我已经从问题中删除了早期代码)。

promiseService(promise是一个测试套件变量,允许我在应用之前对每个测试套件中的promise使用不同的行为,例如在一个测试中拒绝,在另一个测试组中成功)

    mockPromiseService = jasmine.createSpyObj('promiseService', ['getPromise']);
    mockPromiseService.getPromise.andCallFake( function() {
        promise = $q.defer();
        return promise.promise;
    })

正在测试的控制器功能-

$scope.qPromiseCall = function() {
    var timeoutdata = null;
    $timeout(function() {
        promise = promiseService.getPromise();
        promise.then(function (data) {
                timeoutdata = data;
                if (data == "promise success!") {
                    console.log("success");
                } else {
                    console.log("function failure");
                }
            }, function (error) {
                console.log("promise failure")
            }
        )
    }, 250).then(function (data) {
        if(typeof timeoutdata === "undefined" ) {
            console.log("Timed out")
        }
    },function( error ){
        console.log("timed out!");
    });
}

测试(通常我在这里解决或拒绝承诺,但通过不设置它,我正在模拟超时)

it('Timeout logs promise failure', function(){
    spyOn(console, 'log');
    scope.qPromiseCall();
    $timeout.flush(251);
    $rootScope.$apply();
    expect(console.log).toHaveBeenCalledWith("Timed out");
})

首先,我想说您的控制器实现应该是这样的:

$scope.qPromiseCall = function() {
    var timeoutPromise = $timeout(function() {
      canceler.resolve(); //aborts the request when timed out
      console.log("Timed out");
    }, 250); //we set a timeout for 250ms and store the promise in order to be cancelled later if the data does not arrive within 250ms
    var canceler = $q.defer();
    $http.get("data.js", {timeout: canceler.promise} ).success(function(data){
      console.log(data);
      $timeout.cancel(timeoutPromise); //cancel the timer when we get a response within 250ms
    });
  }

您的测试:

it('Timeout occurs', function() {
    spyOn(console, 'log');
    $scope.qPromiseCall();
    $timeout.flush(251); //timeout occurs after 251ms
    //there is no http response to flush because we cancel the response in our code. Trying to  call $httpBackend.flush(); will throw an exception and fail the test
    $scope.$apply();
    expect(console.log).toHaveBeenCalledWith("Timed out");
  })
  it('Timeout does not occur', function() {
    spyOn(console, 'log');
    $scope.qPromiseCall();
    $timeout.flush(230); //set the timeout to occur after 230ms
    $httpBackend.flush(); //the response arrives before the timeout
    $scope.$apply();
    expect(console.log).not.toHaveBeenCalledWith("Timed out");
  })

演示

promiseService.getPromise的另一个例子:

app.factory("promiseService", function($q,$timeout,$http) {
  return {
    getPromise: function() {
      var timeoutPromise = $timeout(function() {
        console.log("Timed out");
        defer.reject("Timed out"); //reject the service in case of timeout
      }, 250);
      var defer = $q.defer();//in a real implementation, we would call an async function and 
                             // resolve the promise after the async function finishes
      $timeout(function(data){//simulating an asynch function. In your app, it could be
                              // $http or something else (this external service should be injected
                              //so that we can mock it in unit testing)
        $timeout.cancel(timeoutPromise); //cancel the timeout 
         defer.resolve(data);
      });
      return defer.promise;
    }
  };
});
app.controller('MainCtrl', function($scope, $timeout, promiseService) {
  $scope.qPromiseCall = function() {
    promiseService.getPromise().then(function(data) {
      console.log(data); 
    });//you could pass a second callback to handle error cases including timeout
  }
});

你的测试类似于上面的例子:

it('Timeout occurs', function() {
    spyOn(console, 'log');
    spyOn($timeout, 'cancel');
    $scope.qPromiseCall();
    $timeout.flush(251); //set it to timeout
    $scope.$apply();
    expect(console.log).toHaveBeenCalledWith("Timed out");
  //expect($timeout.cancel).not.toHaveBeenCalled(); 
  //I also use $timeout to simulate in the code so I cannot check it here because the $timeout is flushed
  //In real app, it is a different service
  })
it('Timeout does not occur', function() {
    spyOn(console, 'log');
    spyOn($timeout, 'cancel');
    $scope.qPromiseCall();
    $timeout.flush(230);//not timeout
    $scope.$apply();
    expect(console.log).not.toHaveBeenCalledWith("Timed out");
    expect($timeout.cancel).toHaveBeenCalled(); //also need to check whether cancel is called
  })

演示

"除非在指定的时间框架内解决,否则无法兑现承诺"的行为似乎非常适合重构为单独的服务/工厂。这将使新服务/工厂和控制器中的代码更加清晰和可重复使用。

控制器,我假设它只是在范围上设置成功/失败:

app.controller('MainCtrl', function($scope, failUnlessResolvedWithin, myPromiseService) {
  failUnlessResolvedWithin(function() {
    return myPromiseService.getPromise();
  }, 250).then(function(result) {
    $scope.result = result;
  }, function(error) {
    $scope.error = error;
  });
});

工厂failUnlessResolvedWithin创建了一个新的promise,它有效地从传入的函数中"截取"了一个promise。它返回一个复制其解析/拒绝行为的新承诺,只是如果在超时时间内没有解析,它也会拒绝承诺:

app.factory('failUnlessResolvedWithin', function($q, $timeout) {
  return function(func, time) {
    var deferred = $q.defer();
    $timeout(function() {
      deferred.reject('Not resolved within ' + time);
    }, time);
    $q.when(func()).then(function(results) {
      deferred.resolve(results);
    }, function(failure) {
      deferred.reject(failure);
    });
    return deferred.promise;
  };
});

这些测试有点棘手(而且很长),但您可以在http://plnkr.co/edit/3e4htwMI5fh595ggZY7h?p=preview。测试的要点是

  • 控制器的测试通过调用$timeout来模拟failUnlessResolvedWithin

    $provide.value('failUnlessResolvedWithin', function(func, time) {
      return $timeout(func, time);
    });
    

    这是可能的,因为"failUnlessResolvedWithin"(故意)在语法上等同于$timeout,并且由于$timeout提供了flush函数来测试各种情况而实现了这一点。

  • 服务本身的测试使用调用$timeout.flush来测试在超时之前/之后解析/拒绝原始承诺的各种情况的行为。

    beforeEach(function() {
      failUnlessResolvedWithin(func, 2)
      .catch(function(error) {
        failResult = error;
      });
    });
    beforeEach(function() {
      $timeout.flush(3);
      $rootScope.$digest();
    });
    it('the failure callback should be called with the error from the service', function() {
      expect(failResult).toBe('Not resolved within 2');
    });   
    

您可以在http://plnkr.co/edit/3e4htwMI5fh595ggZY7h?p=preview

我用一个真实的示例实现了@Michal Charemza的failUnlesResolvedWithin。通过将延迟对象传递给func,它减少了在使用代码"ByUserPosition"中实例化promise的必要性。帮助我处理萤火虫和地理定位。

.factory('failUnlessResolvedWithin', ['$q', '$timeout', function ($q, $timeout) {
    return function(func, time) {
        var deferred = $q.defer();
        $timeout(function() {
            deferred.reject('Not resolved within ' + time);
        }, time);
        func(deferred);
        return deferred.promise;
    }
}])

            $scope.ByUserPosition = function () {
                var resolveBy = 1000 * 30;
                failUnlessResolvedWithin(function (deferred) {
                    navigator.geolocation.getCurrentPosition(
                    function (position) {
                        deferred.resolve({ latitude: position.coords.latitude, longitude: position.coords.longitude });
                    },
                    function (err) {
                        deferred.reject(err);
                    }, {
                        enableHighAccuracy : true,
                        timeout: resolveBy,
                        maximumAge: 0
                    });
                }, resolveBy).then(findByPosition, function (data) {
                    console.log('error', data);
                });
            };

相关内容

  • 没有找到相关文章

最新更新