Controlling how each capture is handled in $ httpBackend.when ()

I am trying to create some jasmine tests in my angular project. I ran into a situation, I'm not sure how best to work.

I am using a response interceptor that can retry the request if it determines the error was a 401 error. It will make a call to update the authorization token and then re-execute the request transparently.

(Orginal Call) → 401? (try and try again): (no return possible)

My problem is this:

$httpBackend.whenPOST('/mymockedendpoint').respond(401, null);

      

This is the behavior I want it to be requested the first time. However, since it also monitors all subsequent requests, my token update works and then it re-issues that request, but instead of returning 200 as it would in production, it still returns 401.

How can I extend the handling of this whenPOST

so that I can control the behavior of any handler? Is it possible?

Right now executing my test is causing an infinite loop because both re-issue the request (since it successfully updated the token) and catches again because the be-be-200 requests return 401).

+3


source to share


1 answer


Instead of using functions based on "when" $httpBackend

, you can use "expect" versions. This will allow you to assert that a specific request is executed in a specific order. The documentation for $ httpBackend describes the differences pretty well:

$ httpBackend.expect - indicates the expected number of requests

$ httpBackend.when - specifies the backend definition

Requesting Expectations and Backend Definitions

A request for expectations provides a way to make statements about requests submitted by an application and to define responses for those requests. The test will fail if the expected requests are not made or they are made in the wrong order.

The backed definitions allow you to define a fake server for your application that doesn't assert if a specific request was made or not, it just returns a prepared response if a request is made. Test whether a request will be received during testing.

With that in mind, try this in your test:



$httpBackend.expectPOST('/mymockedendpoint').respond(401, null);
$httpBackend.expectPOST('/mymockedendpoint').respond(200, { });
$httpBackend.flush();

      

Also, look out for a function $httpBackend.resetExpectations()

that can be useful in this type of scenario.

+3


source







All Articles