如何删除意外的请求:GET data.json? [英] how to remove Unexpected request: GET data.json?

查看:143
本文介绍了如何删除意外的请求:GET data.json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 $ httpBackend ,以测试我的$ HTTP请求..我正在逐渐

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

此错误

Unexpected request: GET data.json
No more request expected

这里是我的测试code

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')
  });

这是我的code
http://plnkr.co/edit/zdfYdtWbnQz22nEbl6V8?p​​=$p$pview

解决方案消除这种误差

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'
  }
  }
  }

})

如果我注释掉这一行的 $ scope.getData(); 或删除此行的 $ scope.getData(); ,然后我的测试是合格,我能够消除这种误差。
我的问题为什么发生这个错误?如果我不能够使用控制器的功能,那么什么是使用这个功能的测试?

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 ?

推荐答案

在初始化的控制器,因为你调用 $ scope.getData() data.json 将是牵强。因此,在初始化测试控制器时,该请求将有每个控制器被初始化时被嘲笑。

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.

,以克服这一点的一种方式是纳克-INIT =的getData()来使用该控制器,以使数据将取出的HTML元素,但仅添加上通过的HTML请求,而不是当控制器被初始化。

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.

这篇关于如何删除意外的请求:GET data.json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆