gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:35:47 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com