1

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?

1 Answer 1

3

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

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

Comments

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.