CitizenX
CitizenX

Reputation: 515

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

I have an AngularJS app that is having some issues in testing.

Method

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;

Unit test:

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();
});

When this test executes, the error Error: Unexpected request: GET http://ip_address/plans/special No more request expected is returned. If I comment out the the httpBackend.flush, the test passes. However, if I change the expect(planService.plans) to a non-existent method, it doesn't fail. Clearly, the expectations are not being called. What's wrong with this?

Upvotes: 2

Views: 9858

Answers (1)

Boris Charpentier
Boris Charpentier

Reputation: 3545

The error :

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

Means that there is actually no call made to that url, start by double checking the url you'r testing.

In test, for promise to be executed you have to call $rootScope.$digest(); (to avoid asynchronous testing, in the same manner that there is a flush method on $httpBackend), if you add that your test should fail, because the promise will be executed.

Upvotes: 3

Related Questions