加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – angular.js如何在每次测试中模拟(或存根)xhr请求

发布时间:2020-12-17 17:44:55 所属栏目:安全 来源:网络整理
导读:在角度js单元测试中,我想为每个测试设置xhr响应(在“it”方法中),而不是在beforeEach方法中,但它似乎不起作用. 这有效 describe('ExampleListCtrl',function(){ var $scope,$httpBackend; beforeEach(inject(function(_$httpBackend_,$rootScope,$controller
在角度js单元测试中,我想为每个测试设置xhr响应(在“it”方法中),而不是在beforeEach方法中,但它似乎不起作用.

这有效

describe('ExampleListCtrl',function(){
  var $scope,$httpBackend;

  beforeEach(inject(function(_$httpBackend_,$rootScope,$controller) {
    $httpBackend = _$httpBackend_;
    $httpBackend.expectGET('examples').respond([]);   // <--- THIS ONE
    $controller(ExampleListCtrl,{$scope: $scope = $rootScope.$new()});
  }));

  it('should create "examples"  with 0 example fetched',function() {
    expect($scope.examples).toBeUndefined();
    $httpBackend.flush();
    expect($scope.examples).toEqual([]);
  });

});

结果

Executed 8 of 8 SUCCESS (0.366 secs / 0.043 secs)

但是当我将expectGet方法移动到每个方法时,这会失败并出现错误.我不知道为什么.

describe('ExampleListCtrl',$controller) {
    $httpBackend = _$httpBackend_;
    $controller(ExampleListCtrl,function() {
    $httpBackend.expectGET('examples').respond([]);  // <--- MOVED TO HERE
    expect($scope.examples).toBeUndefined();
    $httpBackend.flush();
    expect($scope.examples).toEqual([]);
  });
});

这是错误

....
at /Users/me/app/test/unit/controllers/ExampleListCtrlSpec.js:3:1
      Error: No pending request to flush
at Error (<anonymous>)
at Function.$httpBackend.flush (/Users/me/app/test/lib/angular/angular-mocks.js:1171:34)
at null.<anonymous> (/Users/me/app/test/unit/controllers/ExampleListCtrlSpec.js:14:18)

—-编辑—-

按照下面的建议,我已将控制器移出beforeEach,并更改了这样的测试,以便我可以多次测试$httpBackend.expectGET.

describe('ExampleListCtrl',$controller) {
    $httpBackend = _$httpBackend_;
    controller = $controller;
    $scope = $rootScope.$new();
  }));

  it('should create "examples" model with 0 example fetched from xhr',function() {
    $httpBackend.expectGET('examples').respond([]);
    controller(ExampleListCtrl,{$scope: $scope});
    $httpBackend.flush();
    expect($scope.examples).toEqual([]);
  });

});

解决方法

这是因为一旦你实例化你的控制器,它会获取$http,因此,$httBackend.因此,所有期望都应在要求之前作出.

如果你想将你的$httpBackend.expectGet移动到规范(它阻止),那么你需要移动你的$controller(ExempleListCtrl,…也就是在期望之后.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读