2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

As an addendum to this response: we're using a path factory in this project. When the path is hard-specified (i.e. '/plans/special') it seems to fail to mock the whenGET. When the path is specified using the path factory value, it works. I'm going with that the hard-specified path didn't include the server information. Therefore, it was hitting the expected mock. Thanks for the help, @Boris-Charpentier!
This might also occur when the API GET call needs authentication before being fetched by Karma.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.