问题
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:
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.
来源:https://stackoverflow.com/questions/14591730/angularjs-unit-test-for-keypress-event