2

I set up a directive that binds a function for the keydown and keypress events. The directive sets the focus for an input on a form when a shortcut key is entered.

<input type="text" id=txtField1" focus-key="a" />
<input type="text" id=txtField2" focus-key="b" />
<input type="text" id=txtField3" focus-key="c" />

Is it possible to trigger the keypress event for unit testing my directives? Thanks in advance for your help.

Dan
  • 1,539
  • 12
  • 23
Sri Ram
  • 23
  • 1
  • 3
  • In other [thread][1] I've added answer and described how to test keydown. [1]: http://stackoverflow.com/questions/18001169/how-do-i-trigger-a-keyup-keydown-event-in-an-angularjs-unit-test/28146595#28146595 – Maciej Dzikowicki Jan 26 '15 at 08:38

1 Answers1

5

You can use jQuery with AngularJS, and you can do this fairly easily in jQuery with the trigger() API call. You can pass an event into trigger, in this case the event is the

var aEvent = jQuery.Event("keydown");
aEvent.which = 40; //this is the ASCII value of the key you want to press
$("input").trigger(aEvent);

Then repeat for the other characters.

James M
  • 480
  • 3
  • 6
  • What about without the use of jQuery, just with jqLite? We have chosen not to include jQuery in our project (because we don't require it - jqLite is sufficient for our needs). I am not willing to add jQuery as a test-only dependency, as this would cause our unit tests to run in a different environment to production. Any suggestions? – Johnus Aug 21 '14 at 00:03
  • @Johnus I think nowadays I would revise my answer, honestly. Could have a directive instead, or even a scope function that uses the ng-keydown event. That might help with testing as you could just call the function. Not 100% sure though. – James M Sep 18 '14 at 14:11
  • I have a similar code. I have a directive attribute which listens to keypress events and does something on model. in unit test I am triggering like the above comment. But, model is not getting updated :'( – Navaneeth Feb 03 '15 at 17:10
  • @Navaneeth is $digest not firing maybe? I don't know why it wouldn't. Or maybe the test is looking at the wrong model? What happens if you use it outside the test and on a test page? – James M Mar 16 '15 at 16:04
  • @james: I believe it is not a problem with test. The keypress event does not update input value. Let me say in this way. After user presses, events trigger at different levels and at the end the action of updating value of the input happens. So at keypress it won't happen. So model will also be not updated. To unit test the registered callback, I am extracting the callback from $._data data structure and writing unit tests on top of the call back :D :) – Navaneeth Mar 16 '15 at 17:39