问题
我正在尝试测试一些指令(下面是两个指令的代码)。其中之一是“电子邮件”指令(在代码中称为“epost”(挪威语))。这个解决方案应该适用于所有指令,所以现在我只关注这一个。
技术:Angularjs,Jasmine,Requirejs,(grunt和karma在Chrome中运行)
该指令通过两种方式验证电子邮件地址;在upshift和模糊上。我可以轻松测试upshift,如下面的测试所示,但我不知道如何模拟模糊,使指令中的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();
我基于这个链接中的注入和设置进行了操作:To test a custom validation angularjs directive AngularJS中的电子邮件指令包装在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);
});
});
});
});