Tag Archives: $httpBackend

Angularjs-mock testing $http by mocking using httpBackend and flush() not working.

Background

I was writing a unit test for my angularjs app and I ran into the following problem.

I was setting up the test correctly to inject in the $httpBackend to mock out the http calls, but the when I called called the service and then called $httpBackend.flush() it would return an error:

httpBackend no pending request to flush

Which is not what I was expecting.

Other background

When I commented out the $httpBackend.whenGET
The following 2 methods in the afterEach function would not throw an error either.

$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();

This would pass the test even though the expectations were never triggered.

Here is an example of the code I was testing with.

Continue reading

Unit testing angularjs with $http

Angularjs unit testing with $http.

How it all hangs together

When calling external servers to get or push data you can use the $http from angular.  $http has a set of methods like Get, Post and Put like you would expect.

$http callback methods.

It treats the call much like a ajax call where it has a .success method and a .error method which it returns to depending on if the call success or failure.

Scoping of parameters and .success() and .errror()

You can interact with the $scope or $rootScope to set or change data.  The scoping of the .success() and .error() means you cannot use a method level parameter and expect the value to be assigned before the the method ends.  It can go out of scope before it is guaranteed to be set.

Continue reading