Accessing Views In UI Tests Using
When you're writing a UI test, you often want to check that a view is on-screen. If it's a label or a button, you can access it using the text of that label or button. But if that text is long, dynamic, or if you're using some other view, setting an
accessibilityIdentifier to look up is usually a better approach.
Set the property on whichever view you want to access. In this example it's a
UITextField but this works for any
textField.accessibilityIdentifier = "myTextField"
Then in the UI test you can look up the view by that identifier:
let textField = app.textFields["myTextField"] textField.tap() // do whatever you need to now
accessibilityIdentifier is only used in code, it's not presented to the user of your app, even in VoiceOver. So it's safe to use for your tests without worrying about how a user might experience it.
Paul Hudson has written a great cheat sheet for UI testing your iOS app. There are loads of tips like this one in the brilliant Hacking With Swift article.
Apple’s documentation for
accessibilityIdentifier can be found here, and interestingly, explicitly calls out using it for automation.
Published on 4 January 2022