0

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

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 状态的最佳实践方法?

4

1 回答 1

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;
  ...
}]));
于 2013-07-25T14:52:24.487 回答