Reputation: 471
I am writing QUnit tests for an AngularJS factory. Here's the code for the factory:
var app = angular.module('App', []);
app.factory('$groupFactory', function($rootScope, $http) {
return {
'getAll': function(_callback) {
$http.get("get/values/from/server", {
headers: {
'Content-type': 'application/json'
}
}).success(function(data, status, headers, config) {
_callback(data);
}).
error(function(data, status, headers, config) {
_callback(data);
});
},
}
});
Also see the below Qunit test cases. The test-1 gets the http response from the $httpBackend
works, but in test-2, it doesn't.
var $scope,
$rootScope,
$http,
$httpBackend,
$groupFactory,
injector = angular.injector(['ng', 'App', 'ngMockE2E']),
init;
init = {
setup: function() {
$rootScope = injector.get('$rootScope').$new();
$groupFactory = injector.get('$groupFactory');
$httpBackend = injector.get('$httpBackend');
$httpBackend
.when('GET', "get/values/from/server")
.respond({'response': 'success'});
}
};
module('$groupFactory', init);
// test-1
test("getAll", function() {
expect(1);
$groupFactory.getAll(function(data) {
equal(data.response, 'success', "success casse");
start();
});
stop();
});
// test-2
test("getAll", function() {
expect(1);
$httpBackend.expectGET("get/values/from/server").respond(404, {
response: 'failure'
});
$groupFactory.getAll(function(data) {
equal(data.response, 'failure', "failure casse");
start();
});
stop();
});
Any idea why is it not working?
Here is a demo on jsFiddle.
Upvotes: 0
Views: 2834
Reputation: 471
Calling $httpBackend.flush()
after stop()
will work:
stop();
$httpBackend.flush();
Here's the updated demo.
Upvotes: 1