Angular unit tests - httpBackend
Demonstrating usage of module and inject from angular mocks
by Artem
HTML
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.0.5/angular.js"></script>
<script src="http://code.angularjs.org/1.0.5/angular-mocks.js"></script>
JavaScript
// --- SPECS -------------------------
describe('$httpBackend', function () {
it("expects GET http calls and returns mock data", inject(function ($http, $httpBackend) {
var url = '/path/to/resource',
successCallback = jasmine.createSpy();
// Create expectation
$httpBackend.expectGET(url).respond(200, 'mock data');
// Call http service
$http.get(url).success(successCallback);
// callback called only after flush
expect(successCallback).not.toHaveBeenCalled();
// flush response
$httpBackend.flush();
// Verify expectations
// Actual response is [ 'mock data', 200, Function, { method : 'GET', url : '/path/to/resource' } ]
expect(successCallback.mostRecentCall.args).toContain('mock data');
expect(successCallback.mostRecentCall.args[1]).toBe(200);
}));
it("expects POST http calls and returns mock data", inject(function ($http, $httpBackend) {
var url = '/path/to/resource',
data = 'mock data',
header = {'LWSSO': 'token value'},
successCallback = jasmine.createSpy('success'),
errorCallback = jasmine.createSpy('error');
// Create expectation
// headers is a unction that receives http header object and returns true
// if the headers match the current expectation.
$httpBackend.expectPOST(url, data, function(headers) {
// check if the header was send, if it wasn't the expectation won't
// match the request and the test will fail
return headers['LWSSO'] === 'token value';
}).respond(500, 'Oh no!');
// Call http service
$http({
method: 'POST',
url: url,
data: data,
headers: header
}).success(successCallback).error(errorCallback);
// flush response
...