Appium and WebDriverIO
29% COMPLETE
Appium and WebDriverIO - Locate Elements
Exit course
Locate Elements
To interact with elements, you will need to find a reference to the element which you can then use with Appium to locate.
Selector Strategies
Selector strategies offer different ways to locate elements on a page, or in a mobile app. Depending on the device type (iOS or Android), there are various strategies you can use to find an element:
-
Accessibility ID: for XCUITest (iOS) this will look for elements that have a matching
accessibility-id
. On Android, Appium will usecontent-desc
. Using these identifiers make sure your app works well accessibility-wise and it improves your test script, so it's a double win. They can be used as reliable locators as well, as they are less likely to change when developers make UI modifications. -
Native Locators: You can use these locators, targetting iOS or Android elements:
class name
,id
,name
,tag name
,link text
andpartial link text
. - XPath: XPath is a powerful selector strategy that allows locating elements based on their attributes, hierarchy or position in the DOM structure. It provides flexibility and the ability to traverse the DOM tree in any direction. Do note that complex XPath expressions can impact your test performance. Use XPath sparingly and prefer other strategies where possible.
- CSS Selectors: these provide an efficient way to locate elements by using CSS properties. These selectors offer various attribute-based, hierarchy-based and pseudo-class-based selectors. CSS selectors are generally faster and more readable than XPath, so wherever possible, use these.
Best practices when choosing a Locator Strategy
You can choose to mix various locator strategies, or go for a single strategy. When choosing one or more strategies, these best practices might come in use:
- Use Unique and Stable Attributes: Choose attributes that are unique to the element and are unlikely to change during UI modifications. For example, using a class name that is shared among multiple elements may lead to ambiguity and brittle tests.
-
Use Chained Selectors: Combine multiple locators to create a more precise and targeted selector. For example, if a button has the class "submit" and the attribute
data-test-id
, you can use a CSS selector like.submit[data-test-id='button-submit']
to ensure uniqueness. - Try to avoid Positional Locators: Avoid relying on the position of elements in the DOM. Examples include indices or XPath position predicates (for example using [1], [2], etc.). These locators are fragile and prone to break whenever the UI changes.
- Use Page Objects: Implement the Page Object pattern to encapsulate the locators and interactions for each page or component. This improves maintainability and reusability of your test code. If you have a login flow that you need to execute for each test, consider grouping this in a page object which you can then re-use across testcases.