unit-testing – 测试自定义验证角度指令
发布时间:2020-12-17 09:10:06  所属栏目:安全  来源:网络整理 
            导读:这个自定义验证指令是在官方角点的一个例子。 http://docs.angularjs.org/guide/forms 它检查文本输入是否是数字格式。 var INTEGER_REGEXP = /^-?d*$/;app.directive('integer',function() { return { require: 'ngModel',link: function(scope,elm,attrs
                
                
                
            | 
                         
 这个自定义验证指令是在官方角点的一个例子。 
  
http://docs.angularjs.org/guide/forms 它检查文本输入是否是数字格式。 var INTEGER_REGEXP = /^-?d*$/;
app.directive('integer',function() {
  return {
    require: 'ngModel',link: function(scope,elm,attrs,ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (INTEGER_REGEXP.test(viewValue)) {
          // it is valid
          ctrl.$setValidity('integer',true);
          return viewValue;
        } else {
          // it is invalid,return undefined (no model update)
          ctrl.$setValidity('integer',false);
          return undefined;
        }
      });
    }
  };
}); 
 要单元测试这段代码,我写道: describe('directives',function() {
  beforeEach(module('exampleDirective'));
  describe('integer',function() {
    it('should validate an integer',function() {
      inject(function($compile,$rootScope) {
        var element = angular.element(
          '<form name="form">' +
            '<input ng-model="someNum" name="someNum" integer>' +
          '</form>'
          );
        $compile(element)($rootScope);
        $rootScope.$digest();
        element.find('input').val(5);
        expect($rootScope.someNum).toEqual(5);
      });
    });
  });
}); 
 然后我得到这个错误: Expected undefined to equal 5. Error: Expected undefined to equal 5. 我把打印语句放在任何地方看看发生了什么,它看起来像指令从来没有调用。 
 另一个答案的测试应该写成: 
  
  
                          describe('directives',function() {
  var $scope,form;
  beforeEach(module('exampleDirective'));
  beforeEach(inject(function($compile,$rootScope) {
    $scope = $rootScope;
    var element = angular.element(
      '<form name="form">' +
      '<input ng-model="model.somenum" name="somenum" integer />' +
      '</form>'
    );
    $scope.model = { somenum: null }
    $compile(element)($scope);
    form = $scope.form;
  }));
  describe('integer',function() {
    it('should pass with integer',function() {
      form.somenum.$setViewValue('3');
      $scope.$digest();
      expect($scope.model.somenum).toEqual('3');
      expect(form.somenum.$valid).toBe(true);
    });
    it('should not pass with string',function() {
      form.somenum.$setViewValue('a');
      $scope.$digest();
      expect($scope.model.somenum).toBeUndefined();
      expect(form.somenum.$valid).toBe(false);
    });
  });
}); 
 注意$ scope。$ digest()现在在$ setViewValue之后被调用。这将形式设置为“脏”状态,否则它将保持“原始”,这可能不是你想要的。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
推荐文章
            站长推荐
            
        热点阅读
            