AngularJS使用$ httpBackend模拟响应

时间:2016-08-03 19:58:07

标签: angularjs angular-promise httpbackend

由ngMockE2E模块" $ httpBackend拦截的以下HTTP请求永远不会完成。从$httpBackend得到回复的正确方法是什么?

var app = angular.module('app', ['ngMockE2E']);

app.controller('Foo', function(MyHttpService, $scope) {
  MyHttpService.get().then(function(data) {
    $scope.async_data = data;
  });
});

app.factory('MyHttpService', function($http, $q) {
  return {
    get: function() {
      console.log('MyHttpService.get()');
      return $http.get('/test').then(function(data) {
        console.log('$http.get()', data);
        return data;
      });
    }
  }
});

app.run(['$httpBackend', function($httpBackend) {
  $httpBackend
    .whenGET(/^\/test/)
    .respond(function(method, path) {
       console.log(method, path);
       return {method: method, path: path};
    }); 
}]);

这是live example on codepen

1 个答案:

答案 0 :(得分:1)

它不起作用的原因是.respond内的回调没有返回正确的数据,随后无声地失败。 改变如下:

app.run(['$httpBackend', function($httpBackend) {
  $httpBackend
    .whenGET(/^\/test/)
    .respond(function(method, path) {
       console.log(method, path);
       return [200, {method: method, path: path}];
    }); 
}]);

Here a working codepen

相关问题