【问题标题】:setting form to $valid in angular unit test在角度单元测试中将表单设置为 $valid
【发布时间】:2016-04-08 14:59:35
【问题描述】:

我有一个指令,我要测试设置为属性的表单验证。

    restrict: 'A',
    scope: true, 

表单名称由元素attr给出

 $scope.theFormName = elem.attr('name');

我需要了解的是 if 语句

if ($scope.theForm.$valid) {

在我的 beforeEach 中用于我的单元测试

html = angular.element("<div ha-form-validation name=\"name\" class=\"ng-invalid\"></div>");
    $rootScope = $rootScope.$new();
    element = $compile(html)($rootScope);

    $rootScope.$digest(element);

    scope = element.scope();

    scope.name = {
        name: "test",
    };

我已尝试在我的测试中将表单设置为有效

    var form = scope.theFormName.$setValidity("properties", true);

但是 theFormName 正在返回 undefined

 scope.theFormName.$valid  = undefined

有没有办法将其设置为有效?

【问题讨论】:

    标签: javascript angularjs validation unit-testing


    【解决方案1】:

    这里有几个问题:

    1. 您正在编译的元素 (html) 没有包含可以设置为有效的 form 元素。

    2. 您应该在编译html 之前尝试向$scope 添加属性,如下所示:

      var scope = $rootScope.$new();
      scope.name = {
          name: "test"
      };
      element = $compile(html)(scope);
      
      scope.$digest();
      
    3. 我不确定您的指令到底是什么样的,但如果您尝试访问包含它的 form,那么您可以使用:

      require: '^form',
      link: function(scope, element, attrs, formCtrl)
      

      父表单上的角度 FormController 将作为第四个参数 (formCtrl) 注入 link,而不必将表单名称作为元素的属性传递。

    此外,如果您尝试使用 ha-form-validation 进行某种自定义验证,this 可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 2020-06-28
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多