XCUITests — How to Find Matching Element?
Apple has introduced XCUITests framework to automate iOS applications. It’s highly recommended to explore XCUIElementQuery API in detail to find an element.
· XCUIElementQuery — This class is responsible for finding elements in the view using different types of queries. The query should return a unique UI element.
Find UI Element
While writing XCUITest tests for iOS apps, it’s important to find an element in the view. We have to use XCUIElementQuery to find the unique element on the page. There are different techniques to reach a unique element. The most common one is Subscripting.
If we want to find all the buttons in the current view, for example, we can print out all the buttons using XCUIApplication().buttons but if you want to access with the Delete identifier, then we have to use subscript like this
XCUIApplication().buttons["Delete"]
Subscripting will return you the first matching UI element. This is applicable for other UI elements like Static Text, Textfield, etc.
Now, if you don’t know about the identifier and only know the element type then we have to use the script like this
XCUIApplication().buttons.element
Now, if you want an element that will resolve to the index then we have to use the code like this
XCUIApplication().buttons.element(boundBy: 2)
This will returns an element that will use the index into the query’s results to determine which underlying accessibility element it is matched with.
In the above example, we know the element type is buttons and can easily find the matching elements. But assume that, we don’t know the element type or we want to write the locator which is not strict with element type then we can use a script like this
XCUIApplication().descendants(matching: .any).matching(NSPredicate(format: "identifier == 'Delete'")).firstMatch
Find Multiple Elements:
XCUIApplication()
.descendants(matching: .any)
.matching(NSPredicate(format: "identifier == 'Delete'"))
.allElementsBoundByIndex
Conclusion
These are the basic example. By exploring XCUIElementQuery API in detail, you will find elements as per Test Case.
Let me know — along with any questions, comments, or feedback that you might have on https://www.linkedin.com/in/nshthshah.