问题
我正在尝试测试一些指令(下面的代码)。其中之一是“电子邮件”(在代码(挪威语)中称为“epost”)指令。对此的解决方案应该适用于所有人,所以我暂时保留它。
技术:Angularjs、Jasmine、Requirejs(在 Chrome 中运行的 grunt & karma)
该指令以两种方式验证电子邮件地址;在升档和模糊上。正如您在下面的测试中看到的那样,我可以毫无问题地测试升档,但我无法弄清楚如何模拟模糊,以便指令中的 bind('blur') 运行。
我做了什么
我试图捕捉这样的编译元素:
elem = angular.element(html);
element = $compile(elem)($scope);
然后在测试中,我尝试了几种排列以在指令中的绑定函数内使用控制台日志触发模糊。以下都不起作用。它不会触发。
elem.trigger('blur');
element.trigger('blur');
elem.triggerHandler('blur');
element.triggerHandler('blur');
element.blur();
elem.blur();
我基于此注入和设置:测试自定义验证 angularjs 指令
angularjs 中的 email 指令包含在 requirejs 中
define(function() {
var Directive = function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
var pattern = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
elem.bind('blur', function() {
scope.$apply(function () {
if (!elem.val() || pattern.test(elem.val())) {
ctrl.$setValidity('epost', true);
} else {
ctrl.$setValidity('epost', false);
}
});
});
ctrl.$parsers.unshift(function(viewValue) {
if (pattern.test(viewValue)) {
ctrl.$setValidity('epost', true);
return viewValue;
} else {
return undefined;
}
});
}
};
};
return Directive;
});
测试(使用 jasmine 和 requirejs)
define([
'Angular',
'AngularMocks',
], function () {
describe('Directives', function () {
var $scope;
var form;
beforeEach(module('common'));
beforeEach(function () {
var html = '<form name="form">';
html += '<input type="text" id="epost" name="epost" epost="" ng-model="model.epost"/>';
html += '</form>';
inject(function ($compile, $rootScope) {
$scope = $rootScope.$new();
$scope.model = {
epost: null
};
// Compile the element, run digest cycle
var elem = angular.element(html);
$compile(elem)($scope);
$scope.$digest();
form = $scope.form;
});
});
describe('(epost) Given an input field hooked up with the email directive', function () {
var validEmail = 'a@b.no';
var invalidEmail = 'asdf@asdf';
it('should bind data to model and be valid when email is valid on upshift', function () {
form.epost.$setViewValue(validEmail);
expect($scope.model.epost).toBe(validEmail);
expect(form.epost.$valid).toBe(true);
});
});
});
});