I want to unit test a directive that emulates a placeholder, where the input value is cleared only on keyup/down events.
1. The KeyDown event is triggered when the user presses a Key. 2. The KeyUp event is triggered when the user releases a Key.
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.
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.
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With