angularjs - Angular tests: How to expect element events to be triggered? -
i'm decorating forms this:
angular.module('validation').directive('form', function() { homecoming { restrict: 'e', link: function(scope, element) { var inputs = element[0].queryselectorall('[name]'); element.on('submit', function() { (var = 0; < inputs.length; i++) { angular.element(inputs[i]).triggerhandler('blur'); } }); } }; });
now, i'm trying test directive:
describe('directive: form', function() { beforeeach(module('validation')); var $rootscope, $compile, scope, form, input, textarea; function compileelement(elementhtml) { scope = $rootscope.$new(); form = angular.element(elementhtml); input = form.find('input'); textarea = form.find('textarea'); $compile(form)(scope); scope.$digest(); } beforeeach(inject(function(_$rootscope_, _$compile_) { $rootscope = _$rootscope_; $compile = _$compile_; compileelement('<form><input type="text" name="email"><textarea name="message"></textarea></form>'); })); it('should trigger "blur" on inputs when submitted', function() { spyon(input, 'trigger'); form.triggerhandler('submit'); expect(input.trigger).tohavebeencalled(); // expected spy trigger have been called. }); });
but, test fails.
what's right angular way test directive?
you have problems:
1) input = form.find('input');
, angular.element(inputs[i]);
2 different wrapper objects wrapping same underlying dom object.
2) should create spy on triggerhandler
instead.
3) you're working straight dom hard unit-test.
an illustration of is: angular.element(inputs[i])
is not injected have difficulty faking in our unit tests.
to ensure point 1) returns same object. can false angular.element
homecoming pre-trained value input = form.find('input');
//jasmine 1.3: andcallfake //jasmine 2.0: and.callfake angular.element = jasmine.createspy("angular.element").and.callfake(function(){ homecoming input; //return same object created form.find('input'); });
side note: form
angularjs directive, avoid conflicting defined directive, should create directive , apply form
. this:
<form mycustomdirective></form>
i'm not sure if necessary. because we're spying on global function (angular.element) may used in many places, may need save previous function , restore @ end of test. finish source code looks this:
it('should trigger "blur" on inputs when submitted', function() { var angularelement = angular.element; //save previous function angular.element = jasmine.createspy("angular.element").and.callfake(function(){ homecoming input; }); spyon(input, 'triggerhandler'); form.triggerhandler('submit'); angular.element = angularelement; //restore expect(input.triggerhandler).tohavebeencalled(); // expected spy trigger have been called. });
running demo
angularjs jasmine angular-directive
No comments:
Post a Comment