1

My webpage supports keyboard navigation where pressing the "TAB" key switches focus across the webpage items in a specific order. Pressing Enter key on a focussed item opens the popup/selects that item.

My test cases for automation are: 1. Press Tab key across the website and verify the correct item is in focus. 2. Press Enter key on a focussed item and verify that the popup is displayed. 3. Press Enter key on a focussed item and verify that it is selected.

from selenium.webdriver.common.keys import Keys
# Qs: I want to test that the first time I press TAB key, the logo is in focus.          
# Currently. I am unable to achieve that without finding that element.
# How do I include the first element in the test?
first = self.driver.find_element_by_id("logo")
# The following code tabs to the second item on the page and brings it in focus. 
# Qs: How do I test that this item is in focus?
first.send_keys(Keys.TAB)
# How do I tab to the third item on the page without saving the second item 
# in a variable?
# Do I need to find the element in focus in order to select it by sending the 
# RETURN key?

Thanks for your help

user3394432
  • 91
  • 1
  • 7

3 Answers3

1

You can test for focus using execute_script(), and test for document.activeElement

Something like this will return the web element that is currently active:

second = self.driver.execute_script("return document.activeElement")
Richard
  • 8,961
  • 3
  • 38
  • 47
1

You can start from html or body tag:

driver.find_element_by_tag_name("body")

or:

driver.find_element_by_id("logo") # and then...
driver.switch_to_default_content()

Now you can try to click TAB.

To test focus on element you can just click on it and if in result new window should appear - you can check this in .window_handles, for example:

print browser.window_handles
mchfrnc
  • 5,243
  • 5
  • 19
  • 37
0

To tab to an element without saving the previous element in a variable you can use ActionChains actions = ActionChains(driver) actions.send_keys(Keys.TAB) actions.perform()

Just tab in a loop until the element you want to focus is in focus. You can do this by finding the current active element and pressing tab again if it is not equal to the element you want to tab to: https://stackoverflow.com/a/17026711/4163398

Community
  • 1
  • 1
Dave
  • 977
  • 2
  • 12
  • 22