Trying to test an angular service that returns an $http
GET request and the then
handler, but I'm not able to test that the logic actually works inside of the then
function. Here is a basic, truncated version of the service code:
angular.module('app').factory('User', function ($http) {
var User = {};
User.get = function(id) {
return $http.get('/api/users/' + id).then(function (response) {
var user = response.data;
user.customProperty = true;
return user;
});
};
return User;
});
And here is the test:
beforeEach(module('app'));
beforeEach(inject(function(_User_, _$q_, _$httpBackend_, _$rootScope_) {
$q = _$q_;
User = _User_;
$httpBackend = _$httpBackend_;
$scope = _$rootScope_.$new();
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingRequest();
$httpBackend.verifyNoOutstandingExpectation();
});
describe('User factory', function () {
it('gets a user and updates customProperty', function () {
$httpBackend.expectGET('/api/users/123').respond({ id: 123 });
User.get(123).then(function (user) {
expect(user.customProperty).toBe(true); // this never runs
});
$httpBackend.flush();
});
});
I feel like I've tried pretty much everything to test the logic in the then
call, so if someone can offer suggestions I would greatly appreciate it.
Edit: my problem was also due to nonstandard injection practices, so the answer below worked outside of that.
A few things need to be changed
whenGET
instead ofexpectGET
in order to fake a responsethen
callback, set the response to a variable available outside the callback so you can test it in anexpect
callexpect
call is outside any callbacks, so it always runs and shows any failures.Putting it all together:
As can be seen at http://plnkr.co/edit/9zON7ALKnrKpcOVrBupQ?p=preview