Simulate escape key press without jquery

888 Views Asked by At

I would like to (unit) test my AngularJS app without resorting to using jQuery, as jQuery will replace jqLite and in the real app jQuery won't be available either. There are real differences between jQuery and jqLite, so having jQuery available to AngularJS in the unit tests is a risk.

Most of my tests work fine without jQuery now, but I need to trigger a keydown for the escape key, something I can only find out how to do using jQuery. How would I do that in Javascript in a cross browser fashion?

The directive listens for escape keydowns like this:

body.bind('keydown', handledEscapeKey);
var handledEscapeKey = function(e) {
  if (e.which === 27) {
    e.preventDefault();
    scope.$apply(scope.hideTooltip());
  }
};

I've tried this but it doesn't seem to work:

if( window.KeyEvent ) {
  var evObj = $document.createEvent('KeyEvents');
  evObj.initKeyEvent( 'keydown', true, true, $window, false, false, false, false, 27, 0 );
} else {
  var evObj = $document.createEvent('UIEvents');
  evObj.initUIEvent( 'keydown', true, true, $window, 1 );
  evObj.keyCode = 27;
}

elm[0][0].dispatchEvent(evObj);
1

There are 1 best solutions below

1
On

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>