相关疑难解决方法(0)

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

在角度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([]);
  });

});
Run Code Online (Sandbox Code Playgroud)

结果

Executed 8 of 8 SUCCESS (0.366 secs / 0.043 secs)
Run Code Online (Sandbox Code Playgroud)

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

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

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

  it('should create "examples"  with 0 example fetched', function() {
    $httpBackend.expectGET('examples').respond([]);  // …
Run Code Online (Sandbox Code Playgroud)

angularjs

5
推荐指数
1
解决办法
2796
查看次数

标签 统计

angularjs ×1