Angularjs:测试 Controller 功能,它改变了 $scope

标签 angularjs testing jasmine

我正在尝试测试这个 Controller 功能:

$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 ),工厂删除服务器上的帐户。然后该函数删除作用域中的元素,以便删除的元素不再显示。

我的测试看起来像这样:

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 } ].

最佳答案

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

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

关于Angularjs:测试 Controller 功能,它改变了 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452049/

相关文章:

javascript - refetchEvents 不更新日历

javascript - 我怎样才能得到模拟的 react 事件来更新我组件中 ref 的值?

unit-testing - Angular2/Jasmine 期望为空会使浏览器崩溃

javascript - ProtractorJS 规范未运行,浏览器获取数据;仅有的

javascript - AngularJS 循环不工作

angularjs - Jasmine - 任何 bool 值 (jasmine.any(Boolean))

reactjs - 使用 babel、nyc 和 istanbul 插件从 Cypress 获取代码覆盖率?

c# - 如何创建一个辅助函数来调用作为参数传递的其他函数

typescript - Jasmine 监视导入的模块( typescript )

javascript - 使用 angular/rails 优雅降级