Problem
I am trying to check out some directives (the code for both is below). One of them is the "email" (called "epost" in code (Norwegian)) directive. The solution for this should work for all of them, so I keep it for now.
Technologies: Angularjs, Jasmine, Requirements, (grunting and karma, working in Chrome)
The directive checks email addresses in two ways; when raising and blurring. I can check the raise without any problems, as you can see in the test below, but I canβt figure out how to simulate the blur so that the snapping ("blur") in the directive is done.
What I've done
I tried to catch the compiled element as follows:
elem = angular.element(html); element = $compile(elem)($scope);
And then in the test, I tried a few permutations to cause blur using the console log only inside the bind function in the directive. None of the below work. This does not work.
elem.trigger('blur'); element.trigger('blur'); elem.triggerHandler('blur'); element.triggerHandler('blur'); element.blur(); elem.blur();
I based injection and customization on this: To check the custom angularjs validation directive
Email directive in angularjs wrapped in 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; });
Test (using jasmine and 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 };