Angular UI-Router测试范围继承

时间:2013-07-25 14:04:38

标签: angularjs angular-routing

我正在尝试为嵌套状态编写单元测试。状态从父状态继承一些范围元素。在我的测试中,我正在创建控制器,它显然没有父状态的可见性,因此没有继承范围项的可见性。

it('should show the account page', inject(['$controller', 'security', function ($controller, security){
  // set up controller with a scope
  var $scope = $rootScope.$new();

  // the parent controller calls this
  var user = { first: 'First', last: 'Last', email: 'testuser@test.com', gender:'male', hasPassword:true};
  $httpBackend.when('GET', '/api/user/current-user').respond(200, user);
  $controller('AccountViewCtrl', { $scope: $scope});

  $rootScope.$digest();

  // verify the initial setup
  //scope attributes defined on the parent controller
  expect($scope.user).toEqual(user);
  expect($scope.account).toEqual(user);

  // scope attribute defined on the controller
  expect($scope.genders.length).toEqual(2);
  expect($scope.editable).toBe(false);
  expect($scope.editCheck()).toBe(false);
}]));

AccountCtrl定义了所有子状态所需的许多元素。

.controller('AccountCtrl', ['$scope', 'security', function ($scope, security){
  $scope.user = security.requestCurrentUser();
  $scope.account = angular.copy($scope.user);
}])

AccountViewCtrl定义其他元素,但继承父AccountCtrl

中的元素
.controller('AccountViewCtrl', ['$scope', function ($scope) {
  $scope.editable = false;
  $scope.genders = [
    { name: 'Male', value: 'male' },
    { name: 'Female', value: 'female' }
  ];

  $scope.editCheck = function(){
    return $scope.editable;
  };

  ....
}])

测试失败,因为我只是实例化控制器,并且没有父状态和关联元素的可见性。是否有最佳实践方法来测试ui-router状态?

1 个答案:

答案 0 :(得分:0)

范围继承是Angular的一个特性。因此,我认为没有必要在我的测试中进行测试。

我的解决方法是测试AccountCtrl是否有效,然后将值放在其他测试中:

it("should set scope when account Ctrl loaded", inject(['$controller', 'security', function($controller, security){
  // Add your behavior testing code here
  var $scope = $rootScope.$new();
  var user = { first: 'First', last: 'Last', email: 'testuser@test.com', gender:'male', birthday:'password'};
  security.currentUser = user;
  $controller('AccountCtrl', { $scope: $scope});
  $rootScope.$digest();

  // verify the initial setup
  expect($scope.user).toEqual(user);
  expect($scope.account).toEqual(user);
}]));

然后在其他测试中我手动填充值:

it('should set scope on account page', inject(['$controller', 'I18N.MESSAGES', function ($controller, i18nMessages){
  // set up controller with a scope
  var $scope = $rootScope.$new();
  var user = { first: 'First', last: 'Last', email: 'testuser@test.com', gender:'male', birthday:'password'};
  $scope.account = $scope.user = user;
  ...
}]));
相关问题