$httpBackend.verifyNoOutstandingExpectation() 导致 "No response defined !" 错误

$httpBackend.verifyNoOutstandingExpectation() leading to "No response defined !" error

My understanding of $httpBackend.verifyNoOutstandingExpectation() 就是说 "Make sure all of the requests that are $httpBackend.expect()-ed by your tests were made by your code. If any of them weren’t, I’ll throw an exception."

1) 这似乎是多余的。是不是对应的$httpBackend.expect()会失败,从而提醒你?

2) 我在使用 $httpBackend.verifyNoOutstandingExpectation() 时收到 No response defined ! 错误。当我删除 $httpBackend.verifyNoOutstandingExpectation() 时,错误消失并且我的测试通过了。为什么会这样?

admin.controller.spec.js:14 指的是 $httpBackend.verifyNoOutstandingExpectation() 调用。

admin.controller.spec.js

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

  beforeEach(module('mean-starter'));
  beforeEach(inject(function($controller, $rootScope, _$httpBackend_) {
    $httpBackend = _$httpBackend_;
    scope = $rootScope.$new();
    AdminController = $controller('AdminController', {
      $scope: scope
    });
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    // $httpBackend.verifyNoOutstandingRequest();
  });

  it('gets users', function() {
    $httpBackend.expectGET('/users');
  });
});

admin.controller.js

angular
  .module('mean-starter')
  .controller('AdminController', AdminController);

function AdminController(User, Auth, $state) {
  var vm = this;
  User
    .list()
    .success(function(data) {
      vm.users = data;
    })
    .error(function() {
      console.log('Problem getting users.');
    });

  vm.delete = function(id) {
    User
      .delete(id)
      .success(function(data) {
        if (Auth.getCurrentUser()._id === id) Auth.logout(); // deleting yourself
        else $state.reload();
      })
      .error(function() {
        console.log('Problem deleting user.');
      });
  };
}

错误消息清楚地说明了问题 - 您需要先定义预期的响应,然后才能验证是否满足预期。

改变

$httpBackend.expectGET('/users');

$httpBackend.expectGET('/users').respond([{
  //Response object or array
}]);