AngularJS Karma testing "Error: Unexpected request: GET" doesn't seem to be executing request

AngularJS Karma testing "Error: Unexpected request: GET" doesn't seem to be executing request

我有一个 AngularJS 应用程序在测试中遇到了一些问题。

方法

PlanService.prototype.getPlanList = function() {
  this.activeRequest = true;
  return this.PlanFactory.planList().then((function(_this) {
    return function(response) {
      _this.plans = response.plans;
      return _this.activeRequest = false;
    };
  })(this));
};

return PlanService;

单元测试:

var planService;
beforeach(function() {
  module("notRealModuleName");
  inject(function(PlanService) {
    planService = PlanService;
  });
});

...(other tests)

it('should get a list of plans', function() {
  var $httpBackend;
  inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');
  });

  var plans = {"plans": [array of stuff goes here]};
  $httpBackend.whenGET('/plans/special').respond(plans);
  var promise = planService.getPlanList();

  promise.then(function(response) {
     expect(response).toBeDefined();
     expect(planService.plans).toBeDefined();
  });
  $httpBackend.flush();
});

执行此测试时,返回错误Error: Unexpected request: GET http://ip_address/plans/special No more request expected。如果我注释掉 httpBackend.flush,则测试通过。但是,如果我将 expect(planService.plans) 更改为不存在的方法,它不会失败。显然,期望没有被调用。这有什么问题吗?

错误:

Error: Unexpected request: GET http://ip_address/plans/postpaid No more request expected

意味着实际上没有调用 url,首先仔细检查您正在测试的 url。

在测试中,要执行承诺,您必须调用 $rootScope.$digest(); (为了避免异步测试,就像 $httpBackend 上有一个 flush 方法一样),如果你添加你的测试应该失败,因为承诺将被执行。