Mastering Web Application

(Rick Simeone) #1
Chapter 3
$scope : $scope
});
}));

it('should return all users', function () {

//setup expected requests and responses
$httpBackend
.whenGET('http://localhost:3000/databases/ascrum/collections/users').
respond([{name: 'Pawel'}, {name: 'Peter'}]);

//invoke code under test
$scope.queryUsers();

//simulate response
$httpBackend.flush();

//verify results
expect($scope.users.length).toEqual(2);
});

afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
});

First of all we can see that the $httpBackend mock allows us to specify expected
requests (whenGET(...)) and prepare fake responses (respond(...)). There is a whole
family of whenXXX methods for each HTTP verb. The signature of the whenXXX family
of methods is quite flexible, and allows us to specify URLs as regular expressions.


To stub data normally returned from a back-end we can use the respond method. It
is possible to mock response headers as well.


The best part about the $httpBackend mock is that it allows us to get precise control
over responses and their timing. By using the flush() method we are no longer
on the mercy of the asynchronous events, and we can simulate an HTTP response
arriving from a back-end at a chosen moment. The unit tests using the $httpBackend
mock can run synchronously, even if the $http service is asynchronous by design.
This makes unit tests executing fast and in predictable manner.


The verifyNoOutstandingExpectation method verifies that all the expected
calls were made ($http methods invoked and responses flushed), while the
verifyNoOutstandingRequest call makes sure that code under test didn't trigger
any unexpected XHR calls. Using those two methods we can make sure that the code
under the test invokes all the expected methods and only the expected ones.

Free download pdf