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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
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 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: 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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.