Case Study: Locator Chaining in Selenium WebDriver

Cleaner and more readable locators in Selenium tests with Locator Chaining

One Selenium Test Failed

Failure/Error: try_for(2) { expect(select_training_class_page.first_available_date_label_regardless_displayed).to include("SAT") }
RuntimeError:
Timeout after 2 seconds with error: expected "FRI\n30/12" to include "SAT"
Diff:
@@ -1,2 +1,3 @@
-SAT
+FRI
+30/12

Analysis

The Problem — Multiple Elements

def first_available_date_label
driver.find_element(:xpath,
"//div[@class='carousel-item carousel-fixed-item active']//li/div/div[@class='noti-count' and text()='1']/../..").text
end
elems = driver.find_elements(:xpath,
"//div[@class='carousel-item carousel-fixed-item active']//li/div/div[@class='noti-count' and text()='1']")
puts elems.count

The Solution — Locator Chaining

elems = driver.find_elements(:xpath, "//div[@class='carousel-item carousel-fixed-item active']//li/div/div[@class='noti-count' and text()='1']")
# only keep elements that are visible
display_elems = elems.select{|x| x.displayed? }
the_notification_badge_element = display_elems.first
<!-- parent 2 - goal-->
<div>
<!-- parent 1 -->
<div class="noti-count">
1 <!-- starting point -->
</div>
Sat
</div>
the_notification_badge_element.find_element(:xpath, "../..").text
Run test steps to return tab text, in TestWise Debugging mode.
def first_available_date_label
elems = driver.find_elements(:xpath, "//div[@class='carousel-item carousel-fixed-item active']//li/div/div[@class='noti-count' and text()='1']")
display_elems = elems.select{|x| x.displayed? }
the_notification_badge_element = display_elems.first
the_notification_badge_element.find_element(:xpath, "../..").text
end
driver.find_element(:xxx, "a").find_element(:yyy, "b")

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store