UI Testing with Xcode: How to find a button that has no title?
Asked Answered
W

2

9

I have some buttons in my user interface that only display an image and no title. How can I access them during a UI Test? window.buttons["delete"].click() doesn't find the button due to lack of title. And I cannot set the title because the image has some transparency.

World answered 4/6, 2017 at 16:15 Comment(0)
W
13

You should set an accessibilityIdentifier. This is a non-user-facing property which was designed to allow you to identify elements in your UI tests. It was introduced to stop people from abusing accessibilityLabel, which people would previously use for identifying things in their tests, but which had an effect on the experience of Voiceover users, who hear the contents of accessibilityLabel when they select an element.

// app code
let myButton: UIButton!
myButton.accessibilityIdentifier = "deleteButton"

// test code
let app = XCUIApplication()
let deleteButton = app.buttons["deleteButton"]
Wame answered 5/6, 2017 at 11:8 Comment(0)
W
3

You can find buttons through the accessibilityLabel. So, first set the label:

deleteButton.setAccessibilityLabel("delete")

And then you can access it as normal with:

 untitledWindow.buttons["delete"].click()
World answered 4/6, 2017 at 16:15 Comment(1)
This does work; however, be aware that the accessibility label is user-facing. The accessibility identifier is preferable, since it does not affect the user. Set the identifier in code, as shown in @Oletha's answer, or via Interface Builder. If one does want (or need) to use the label instead for some reason, though, make sure to name it something that would make sense to a person using voiceover.Mohsen

© 2022 - 2024 — McMap. All rights reserved.