Description
While creating a Web Testcase, there may be a need to use a keypress event in the script. Keypresses can be used to do a variety of actions including pressing up, down, or enter in your script.
Solution
In order to utilize keypress events, a JavaScript step needs to be added in the Web Testcase. At the necessary location in the Testcase, add the following step:
Step type: Function
Step contents: JavaScript("var X = document.createEvent('Events'); X.initEvent('keydown', true, true); X.keyCode = KEYCODE_VALUE; X.which = KEYCODE_VALUE; document.querySelector('ID_OR_CLASS_SELECTOR').dispatchEvent(X);");Wait("1000");
Where X is the variable name, KEYCODE_VALUE is the corresponding keycode for the key, and ID_OR_CLASS_SELECTOR is the selector from the web page code.
Note: The attached document includes a list of keys and their keycodes.
Example: Down Arrow
Step type: Function
Step contents: JavaScript("var d = document.createEvent('Events'); d.initEvent('keydown', true, true); d.keyCode = 40; d.which = 40; document.querySelector('#input_MapLocation_search').dispatchEvent(d);");Wait("1000");
Where d is the variable name, 40 is the keycode for the down arrow, and #input_MapLocation_search is the selector from the web page code.
Example: Enter
Step type: Function
Step contents: JavaScript("var e = document.createEvent('Events'); e.initEvent('keydown', true, true); e.keyCode = 13; e.which = 13; document.querySelector('#input_MapLocation_search').dispatchEvent(e);");Wait("1000");
Where e is the variable name, 13 is the keycode for enter, and #input_MapLocation_search is the selector from the web page code.
Note: The scripts above have to be modified depending on the web page code.
Comments
0 comments
Please sign in to leave a comment.