0

I am trying to make a demo of $http request and test that service also..I do like this

.controller('cntrl',function($scope,appfactory,$http){

  $scope.data=[];
  appfactory.setValue('test abc');

  $scope.getData=function(){
    $http.get('data.json').success(function(data){
      console.log(JSON.stringify(data))
      $scope.data=data;
    }).error(function(data){
        console.log(JSON.stringify(data))
    })
  }
  $scope.getData();
  $scope.toggle=function(){
      if(appfactory.mode()=='a'){
    $scope.message='naveen'
  }else {
     if(appfactory.mode()=='b'){
       $scope.message='parveen'
  }
  }
  }

})

I load that data from json file and display it on view..But when I try to test that application ..I got error why ? how to remove that error

beforeEach(inject(function($rootScope,$controller,appfactory,_$httpBackend_) {
    $scope = $rootScope.$new();  
    $httpBackend=_$httpBackend_;

      createController = function() {
       return $controller('cntrl', {'$scope' : $scope });
     };

}));



   it("tracks that the spy was called", function() {
    var response=[{"name":"naveen"},{"name":"parveen"}]
    $httpBackend.expectGET('data.json').respond(response);
         var controller = createController();

     $scope.getData();
     $httpBackend.flush();

     expect($scope.data[0].name).toEqual('naveen')
  });


})

here is my code http://plnkr.co/edit/zdfYdtWbnQz22nEbl6V8?p=preview

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
user5711656
  • 3,310
  • 4
  • 33
  • 70

1 Answers1

0

http call to get data is effectively getting called twice in the test. One is when the controller is initialized (because you're calling $scope.getData()) and the second is when you manually call $scope.getData() in the spec.

And your expectation is only mocked once (before controller initialisation). To fix the test (to mimic what the controller is actually doing), the expectation has to be set once more before $scope.getData() is called.

See plunker: http://plnkr.co/edit/eLPOZTCgkSfoACLJsVZo?p=preview

OR

You can replace the expectGET with whenGET which doesn't fail the test if the resource is not called. BUT since you're expecting expect($scope.data[0].name).toEqual('naveen') where 'naveen' comes from the http respose, that change should be fine.

Chanthu
  • 1,794
  • 1
  • 15
  • 22
  • P.S. Is this post related? http://stackoverflow.com/questions/34562051/how-to-remove-unexpected-request-get-data-json – Chanthu Jan 02 '16 at 06:44