I am trying to test $http calls inside services which, upon $http response, store the response data in service itself (does not return response to controller). Most examples I found (even AngularJs documentation) are testing $http calls in controller. For ex:
app.factory('dataFactory', function($http){
return {
getData: function(){
return $http.get('https://some-url');
}
}
});
app.controller('MainCtrl', function($scope, dataFactory, $http) {
$scope.name = 'World';
dataFactory.getData().success(function(data){
$scope.data = data;
})
});
The unit test for this code is:
describe('with httpBackend', function() {
beforeEach(inject(function($controller, $rootScope, $httpBackend) {
$scope = $rootScope.$new();
$httpBackend.when('GET', 'https://some-url')
.respond({things: 'and stuff'});
MainCtrl = $controller('MainCtrl', { $scope: $scope });
$httpBackend.flush();
}));
it('should set data to "things and stuff"', function() {
expect($scope.data).toEqual({
things: 'and stuff'
});
});
});
But in my services, I am making the calls in following fashion:
app.service('dataService', function($http) {
var self = this;
this.getData = function() {
$http.get('https://some-url/')
.then(
function success(response) {
self.data = response.data
},
function error(msg) {
console.log(msg);
}
);
};
});
For this, I will need to unit test the service and not the controller.
EDIT: Below is the unit-test I've written (which is passing, but not sure it's the correct approach):
describe('.getData()', function() {
beforeEach(inject(function($httpBackend) {
$httpBackend.when('GET', 'https://some-url/')
.respond({data: 'sample data'});
dataService.getData();
$httpBackend.flush();
}));
it('should store data correctly', function() {
expect(dataService.data).toEqual({data: 'sample data'});
});
});
Need some help regarding the unit-testing approach I should follow to test services with $http calls (and store data).