how to remove Unexpected request: GET data.json?

非 Y 不嫁゛ 提交于 2020-01-03 03:48:25

问题


I am trying to use $httpBackend to test my $http request ..i AM getting

this error

Unexpected request: GET data.json
No more request expected

here is my testing code

beforeEach(inject(function($rootScope,$controller,appfactory,_$httpBackend_) {
    $scope = $rootScope.$new();  
    $httpBackend=_$httpBackend_;
     ctrl = $controller('cntrl', {$scope: $scope});
     fac=appfactory;
    modeSpy= spyOn(fac, 'mode').and.returnValue('a');

}));



  it('test true value',function(){
    expect(true).toBeTruthy()
  })

   it('check message value',function(){
     $scope.toggle();
   expect($scope.message).toEqual('naveen')
  })

   it("tracks that the spy was called", function() {
    //expect(fac.setValue).toHaveBeenCalled();
    var response=[{"name":"naveen"},{"name":"parveen"}]
    $httpBackend.expectGET('data.json').respond(response);
     $scope.getData();
     $httpBackend.flush();

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

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

Solution to remove this error

I have this controller
.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'
  }
  }
  }

})

if i comment out this line $scope.getData(); or remove this line $scope.getData(); then my test is pass and I am able to remove this error . My Question why this error occurred? If am not able to use the function in controller then what is the use of testing of this function ?


回答1:


When initialising the controller because you're calling $scope.getData(), data.json will be fetched. So, when initialising the controller in test, that request would have to be mocked every time controller is initialised.

One way to overcome this is to add ng-init="getData()" to the html element using this controller, so that the data would be fetched but only on request by the html and not when controller is initialized.



来源:https://stackoverflow.com/questions/34562051/how-to-remove-unexpected-request-get-data-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!