0

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).

Rishabh
  • 900
  • 10
  • 30
  • 1
    This could help - http://stackoverflow.com/a/40115646/2622292 Your `dataService.getData();` and `$httpBackend.flush();` calls should be inside the `it` block and not the `beforeEach` block – SiddAjmera Oct 19 '16 at 18:40
  • 1
    Also ideally `dataService` service instead of resolving the promise inside itself should return a promise and that promise should be resolved inside the code that is leveraging this service. There are a few things I've mentioned here that might help you understand better - http://stackoverflow.com/a/40114738/2622292 – SiddAjmera Oct 19 '16 at 18:44
  • 1
    @Rishabh your approach of solving it using `$httpBackend` is correct – tanmay Oct 20 '16 at 03:20

0 Answers0