Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I need to make my application log a user in with saved credentials and retry a request on a 401 and I'm having a hard time testing it because I need the initial call to return a 401, but then return a 200 after the login request happens again.

Here is my test so far:

it("should call login if the status is 401", function() {
  $httpBackend.whenGET(api.baseUrl + "/auth/login").respond(200);
  $httpBackend.whenGET(api.baseUrl + "/practice/active").respond(401);

  api.practiceActiveInquery(function(result) {
    expect(login.fn).toHaveBeenCalled();
  });

  $httpBackend.flush();

});

The problem is I need the whenGET of /practice/active to respond with a 200 after it's called once with the 401, or I get caught in a circle. Or am I thinking about how to test an http interceptor completely wrong?

share|improve this question
up vote 3 down vote accepted

For this, you want to use expectGET instead of whenGET. expectGET only fulfills one request at a time, so you can change the response each time a request is made. Something like this:

it("should call login if the status is 401", function() {
  $httpBackend.whenGET(api.baseUrl + "/auth/login").respond(200);
  $httpBackend.expectGET(api.baseUrl + "/practice/active").respond(401); //will return 401 the 1st time
  $httpBackend.expectGET(api.baseUrl + "/practice/active").respond(200); //will return 200 the 2nd time

  api.practiceActiveInquery(function(result) {
    expect(login.fn).toHaveBeenCalled();
  });

  $httpBackend.flush();

});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.