相关疑难解决方法(0)

测试自定义验证angularjs指令

此自定义验证指令是官方角度站点上提供的示例. 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;
        }
      });
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

为了对这段代码进行单元测试,我写道:

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" …
Run Code Online (Sandbox Code Playgroud)

unit-testing angularjs angularjs-directive

75
推荐指数
2
解决办法
4万
查看次数