How to Press Keyboard Keys
Intro
On occasion, you'll come across functionality that requires the use of keyboard key presses in your tests.
Perhaps you'll need to tab to traverse from one portion of the page to another, back out of some kind of menu or overlay with the escape key, or even submit a form with Enter.
But how do you do it and where do you start?
A Solution
You can easily issue a key press by using the SendKeys command. This can be done to a specific element, or
generically with Selenium's Action Builder (which has been documented on
the Selenium Actions page for Building Advanced User Interactions).
Either approach will send a key press. The latter approach will send it to the element that's currently in focus in the browser (so you don't have to specify a locator along with it), whereas the prior approach will send the key press directly to the element found.
You can see a full list of Selenium's available keyboard keys here.
Let's try out a couple of examples.
Example
Let's use an example from the-internet that displays which key has been pressed.
In the first test, we find an element that's visible (the one that contains the example on the page, with the id
target) and send the space key to it. Then we check the result text on the page.
Alternatively, we can also issue a key press without finding an element first, with the Actions API. The key goes to the element that's currently in focus. That's what the second test does, with the tab key.
Expected Behavior
- Open the browser
- Visit the page
- Find the element and send the space key to it (first test), or send the tab key to the element in focus (second test)
- Find the result text on the page and check that it's what we expect
- Close the browser
Summary
If you have a specific element that you want to issue key presses to, then finding the element first is the way to go. If you don't have a receiving element, or you need to string together multiple key presses, then the Actions API is what you should use.
Happy Testing!
Special Thanks

Authors

