angularjs - 使用 $validators 单元测试 Angular 表单验证

标签 angularjs validation unit-testing jasmine

我的 webapp 正在使用 Angular 1.4.8 .我有一个使用 验证表单输入的指令$验证器 .只有以数字 5、6 和 9 开头并包含 8 个数字的输入才有效。

angular
    .module('directive.customNumber', [])
    .directive('customNumber', customNumber);

function customNumber() {
    var REGEXP = /^([569][0-9]{7})/;

    return {
        require: ['ngModel', '^form'],
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$validators.customNumber = function(modelValue, viewValue) {
                if(ctrl.$isEmpty(modelValue)) {
                    // consider empty models to be valid
                    return true;
                }
                return REGEXP.test(viewValue);
            };
        }
    };
}

用法:
<form name="form">
    <input type="text" name="myInput" custom-number>
</form>

现在我想使用 为这个指令编写一个单元测试 Jasmine .这是我的测试用例:
describe('Directive', function() {
    var $scope;

    beforeEach(function() {
        module('directive.customNumber');
        inject(function($rootScope, $compile) {
            $scope = $rootScope;
            var template = '<form name="form"><input type="text" name="myInput" custom-number></form>';
            $compile(template)($scope);
            $scope.digest();
        });
    });

    it('should not accept invalid input', function() {
        var form = $scope.form;
        form.myInput.$setViewValue('abc');

        expect(form.$valid).toBeFalsy();
        expect(form.myInput.$error.mobile).toBeDefined();
    });
});

运行这个会抛出一个错误 "TypeError: Cannot set property 'customNumber' of undefined在这一行:
ctrl.$validators.customNumber = function(....

我不知道为什么 $validators在测试中变得未定义,但在正常环境中工作正常。即使我通过手动创建 $validators 摆脱了这个错误对象使用前,测试失败,原因是customNumber验证器永远不会运行(通过日志知道),所以 form.$valid永远是真的。

如何正确测试此指令?

最佳答案

在你的指令 ctrl 是一个数组 whare ctrl[0] 是 ngModel 而 ctrl[1] 是 formController

关于angularjs - 使用 $validators 单元测试 Angular 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35057917/

相关文章:

javascript - 从使用动态加载的页面进行 Ajax 加载

validation - <h :inputXxx validator> attribute and <f:validator> tag 之间的差异

unit-testing - Visual Studio 2017 : Azure functions unit test and local. settings.json 问题

java - 支柱2.5 : Validation occurring but no message displayed

C# 测试 - 构造函数调用中的模拟类

jquery - 如何为 Chrome 编写 Greasemonkey 脚本以便对其进行单元测试?

javascript - 来自 url 的 Angularjs json 不起作用,但在本地工作

jquery - 如何在轮播中添加输入字段?

javascript - Visual Studio 与 WebStorm 中的 Typescript 编译——两者都使用 Node.js 进行编译吗?

.net - 如何在验证之前进行正则表达式修剪?