-->

AngularJS - Using ngMockE2E $httpBackend how can I

2019-08-12 07:28发布

问题:

I'd like to delay the response to the following whenGET:

$httpBackend.whenGET(/^foobar/).respond(function () {
  return [200,{}];
});

However it seems impossible using $timeout to do this synchronously, so I'm not sure how to approach this?

回答1:

If you want to delay only a specific response, than you may delay assignment of the reponse to scope property.

If you wrap your call into your custom service method, than you may wrap the response into the promise and resolve it when needed:

JS:

angular.module('app').service('myService', function($q, $timeout){

 this.getData = function() {
    var delay = 300,
        origPromise = $http.get('someUrl'),
        deferred = $q.defer();
    $timeout(function() {
       deferred.resolve(origPromise);
    }, delay);

    return defered.promise;
 };

});

[EDIT]:

To set the delay to all requests, you may apply this solution to the response interceptor