Sending keydown to Angular directive using jQuery.trigger ()

I created an editing directive to wrap the html input in a fancy frame.

Now I am creating a unit test to verify that as soon as I type in the input, the dirty state of the form controller is set.

I use jQuery.trigger () to mimic this, but get nothing ...

var input = $('input'); var e = $.Event('keydown'); e.which = 'x'.charCodeAt(0); e.keyCode = 'x'.charCodeAt(0); input[0].focus(); input.trigger(e); 

I have a plunker here

What am I doing wrong?

Thanks!

+3
source share
1 answer

From the answer to a similar question:

The error you make is what you expect from the jQuery trigger method. If you look at the code, you will see that it actually executes the event handlers processed by jQuery and not DOM Level 3. Since it only executes jQuery, you will not raise the change event that you need to activate the value of the text field property.

Instead, you can update the input value and trigger a change or input event:

 input.val('x').trigger('input'); 

However, when doing this inside the controller in a real application (as opposed to the unit test environment) you need to exit the $ digest cycle or get the $apply already in progress error.

You can do this, for example, using setTimeout :

 $scope.trigger = function() { setTimeout(function() { $('input').val('x').trigger('input'); }); }; 

You also need to make sure that you load jQuery before AngularJS. If you do not, Angular will use jqLite. jqLite uses addEventHandler to register event handlers, and handlers registered this way are not triggered by the jQuery trigger function.

Demo of the updated code: http://plnkr.co/edit/u3ZWXWLvOjbKWlY8JEM5?p=preview

In unit testing:

 it('should work', function() { var element = $compile('<form name="form"><edit ng-model="name"></edit></form>')($scope); $rootScope.$digest(); var scope = element.scope(), form = scope.form, input = element.find('input'); expect(form.$dirty).toBe(false); input.val('x').trigger('input'); expect(form.$dirty).toBe(true); }); 

Unit test demo: http://plnkr.co/edit/Emc3dIlDaxXyE9U6dEG6?p=preview

+5
source

All Articles