Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger a keyup/keydown event in an angularjs unit test?

I want to unit test a directive that emulates a placeholder, where the input value is cleared only on keyup/down events.

like image 944
Chandra Avatar asked Aug 01 '13 17:08

Chandra


People also ask

What is Keyup and Keydown in angular?

1. The KeyDown event is triggered when the user presses a Key. 2. The KeyUp event is triggered when the user releases a Key.

What is the use of Keydown and Keyup events?

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress . An uppercase "A" is reported as 65 by all events.

What is Ng Keyup used for?

The ng-keyup directive tells AngularJS what to do when the keyboard is used on the specific HTML element. The ng-keyup directive from AngularJS will not override the element's original onkeyup event, both will be executed.


2 Answers

You need to create an event programatically and trigger it. To do so including jQuery for unit tests is quite useful. For example, you could write a simple utility like this:

  var triggerKeyDown = function (element, keyCode) {     var e = $.Event("keydown");     e.which = keyCode;     element.trigger(e);   }; 

and then use it in your unit test like so:

triggerKeyDown(element, 13); 

You can see this technique in action in the http://angular-ui.github.io/bootstrap/ project here: https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/test/typeahead.spec.js

Disclaimer: let's be precise here: I'm not advocating using jQuery with AngularJS! I'm just saying that it is a useful DOM manipulation utility for writing tests interacting with the DOM.

To make the above code work without jQuery, change:

$.Event('keydown') 

to:

angular.element.Event('keydown') 
like image 124
pkozlowski.opensource Avatar answered Sep 28 '22 08:09

pkozlowski.opensource


I had issues with using accepted answer. I found other soultion.

var e = new window.KeyboardEvent('keydown', {   bubbles: true,   cancelable: true,   shiftKey: true });  delete e.keyCode; Object.defineProperty(e, 'keyCode', {'value': 27});  $document[0].dispatchEvent(e); 

Working example can be found here

like image 44
Maciej Dzikowicki Avatar answered Sep 28 '22 09:09

Maciej Dzikowicki