在将下面的测试从angularjs 1.6.10版本迁移到1.7.3 ChangeLog
时遇到了一些麻烦var invalid = [
'#@%^%#$@#$@#.com',
'email.example.com',
'email@example@example.com',
'あいうえお@example.com',
//... etc
];
invalid.forEach(function(email){
it(email + ' is a valid email', function(){
inject(function($compile, $rootScope) {
var element = $compile('<input s2-email ng-model="value" />')($rootScope);
$rootScope.$digest();
expect(element).toBeValid();
expect(element).toBePristine();
$rootScope.$apply(function() {
$rootScope.value = email;
});
expect(element).toBeInvalid();
dealoc(element);
});
});
});
错误:
PhantomJS 2.1.1(Linux 0.0.0)S2指令此 是“确实” notallowed@example.com,是有效的电子邮件,失败了TypeError: null不是对象(评估'context.createDocumentFragment') buildFragment@/home/gon250user/Documents/myApp/frontend/webapp/node_modules/jquery/dist/jquery.js:4745:21 domManip@/home/gon250user/Documents/myApp/frontend/webapp/node_modules/jquery/dist/jquery.js:5709:27 append@/home/gon250user/Documents/myApp/frontend/webapp/node_modules/jquery/dist/jquery.js:5898:18 /home/gon250user/Documents/myApp/frontend/webapp/test/spec/directivesSpec.js:113:33 invoke@/home/gon250user/Documents/myApp/frontend/webapp/node_modules/angular/angular.js:5121:24 WorkFn@/home/gon250user/Documents/myApp/frontend/webapp/node_modules/angular-mocks/angular-mocks.js:3439:26 inject@/home/gon250user/Documents/myApp/frontend/webapp/node_modules/angular-mocks/angular-mocks.js:3409:46 /home/gon250user/Documents/myApp/frontend/webapp/test/spec/directivesSpec.js:108:19 inject@/home/gon250user/Documents/myApp/frontend/webapp/node_modules/angular-mocks/angular-mocks.js:3406:28 /home/gon250user/Documents/silverfinch/frontend/webapp/test/spec/directivesSpec.js:108:19
到目前为止,我在文档中发现的是here,所以我已经尝试过了:
invalid.forEach(function(email) {
it(email + ' is a valid email', function(){
inject(function($compile, $rootScope, $rootElement, $document) {
var element = $compile('<input s2-email ng-model="value" />')($rootScope);
$rootElement.append(element);
$document.append($rootElement);
$rootScope.$digest();
expect(element).toBeValid();
expect(element).toBePristine();
$rootScope.$apply(function() {
$rootScope.value = email;
});
expect(element).toBeInvalid();
dealoc(element);
});
});
});
注意:指令
angular.module('s2').directive('s2Email', function() {
var EMAIL_REGEXP = /^[a-z0-9!.....*$/i;
return {
require: '?ngModel',
restrict: '',
link: function(scope, elm, attrs, ngModel) {
function s2EmailValidator(modelValue) {
if ((modelValue === null || modelValue === undefined || modelValue === '') || EMAIL_REGEXP.test(modelValue)) {
ngModel.$setValidity('s2-email', true);
return modelValue;
} else {
ngModel.$setValidity('s2-email', false);
return undefined;
}
}
ngModel.$parsers.unshift(s2EmailValidator);
ngModel.$formatters.unshift(s2EmailValidator);
}
};
});