Angularjs:测试控制器函数,它改变$ scope

时间:2015-05-26 07:21:58

标签: angularjs testing jasmine

我试图测试这个控制器功能:

$scope.deleteAccount = function(account) {

  Account.deleteAccount(account._id)
  .then(function() {
    angular.forEach($scope.accounts, function(a, i) {
      if (a === account) {
        $scope.accounts.splice(i, 1);
      }
    });
  })
  .catch(function(err) {
    $scope.errors.other = err.message;
  });
};   

它位于管理页面上。该函数调用工厂(带有promise),工厂删除服务器上的Account。然后该函数删除范围中的元素,以便不再显示已删除的元素。

我的测试看起来像这样:

beforeEach(inject(function ($controller, $rootScope, _$location_, _$httpBackend_) {

    $scope = $rootScope.$new();
    $location = _$location_;
    $httpBackend = _$httpBackend_;
    fakeResponse = '';

    AdminAccountCtrl = $controller('AdminAccountCtrl', {
      $scope: $scope
    });
    $location.path('/admin/account');
}));

it('test delete account', function () {
    expect($location.path()).toBe('/admin/account');

    $httpBackend.expectGET('/api/accounts').respond([{_id: 1}, {_id: 2}, {_id: 3}]);
    $httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
    $httpBackend.when('DELETE', '/api/accounts/1').respond(fakeResponse);
    $httpBackend.flush();

    $scope.deleteAccount($scope.accounts[0]);
    expect($scope.accounts).toEqual([{_id: 2}, {_id: 3}]);
});

可悲的是结果是:

Expected [ { _id : 1 }, { _id : 2 }, { _id : 3 } ] to equal [ { _id : 2 }, { _id : 3 } ].

1 个答案:

答案 0 :(得分:0)

尝试在$scope.$digest()之后调用deleteAccount。这是必需的,因为测试不像浏览器中正常运行的那样具有摘要周期。

$scope.deleteAccount($scope.accounts[0]);
$scope.$digest();
expect($scope.accounts).toEqual([{_id: 2}, {_id: 3}]);