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