Element Queries and Accessibility Identifiers
On this page
Every interaction in XCUITest starts with finding an element. This chapter shows how queries work, which ways of identifying an element survive app changes, and how to see the element tree XCUITest is working with.
Queries are lazy descriptions#
app.buttons["login.submit"] does not search the screen when you write it. It builds an XCUIElement that describes how to find the element: "descendants of the app of type Button, matching login.submit". The search happens each time you use it: when you read .exists, call .tap() or read .label. That has two consequences:
- You can keep an element in a variable or property and reuse it across screens; it is re-resolved every time.
- If the description matches nothing at that moment, actions fail ("No matches found"), and if it matches more than one, actions fail too ("Multiple matching elements found"). A query that is ambiguous is a bug in the test, not bad luck.
The building blocks are element-type queries on XCUIApplication (or on any element):
| Query | SwiftUI / UIKit element |
|---|---|
app.buttons |
Button, UIButton, tappable list rows built from a Button
|
app.staticTexts |
Text, UILabel
|
app.textFields |
TextField, UITextField
|
app.secureTextFields |
SecureField, secure UITextField
|
app.navigationBars |
the navigation bar of a NavigationStack / UINavigationController
|
app.cells, app.tables, app.collectionViews
|
list and table content |
app.activityIndicators |
ProgressView, UIActivityIndicatorView
|
app.otherElements |
containers and anything without a more specific type |
app.descendants(matching: .any) |
everything, regardless of type |
Picking the wrong type is the most common reason a query finds nothing. In the Tasks app the password field is a SecureField, so app.textFields["login.password"] never matches; it has to be app.secureTextFields["login.password"].
Accessibility identifiers#
Subscripting a query with a string matches an element whose accessibility identifier or label equals that string. Labels are what users see and VoiceOver reads, so they change with copy edits and translations. Accessibility identifiers are strings meant for automation: users never see them and they do not change when the language does. Add them to every element a test touches.
In SwiftUI:
TextField("Email", text: $email)
.textFieldStyle(.roundedBorder)
.accessibilityIdentifier("login.email")
SecureField("Password", text: $password)
.textFieldStyle(.roundedBorder)
.accessibilityIdentifier("login.password")
Button("Sign in") { signIn() }
.buttonStyle(.borderedProminent)
.disabled(email.isEmpty || password.isEmpty || busy)
.accessibilityIdentifier("login.submit")
In UIKit the property is the same name: emailField.accessibilityIdentifier = "login.email".
A naming scheme such as screen.element keeps identifiers unique across the app and makes failure messages readable. Do not misuse accessibilityLabel for test hooks: VoiceOver users hear the label, so "login_submit_btn" there is an accessibility bug.
For repeated elements, give every row the same identifier and tell them apart by label. The task rows in the Tasks app:
ForEach(store.tasks) { item in
Button {
store.toggle(item)
} label: {
HStack {
Image(systemName: item.done ? "checkmark.circle.fill" : "circle")
Text(item.title)
}
}
.accessibilityIdentifier("task.row")
.accessibilityLabel(item.title)
.accessibilityValue(item.done ? "done" : "open")
}
The explicit label makes the row read as its title (instead of "circle, Buy milk"), and the value exposes its state to VoiceOver and to tests alike. Good accessibility and good testability are the same work here; the Accessibility Testing course covers the user side.
Your tests use app.buttons["Sign in"]. They pass in English and fail when the suite runs with the German localisation. What is the fix?
Identifiers are not localised and not shown to users, so they are stable across languages. Forcing an English label breaks VoiceOver for German users, and an index breaks as soon as another button appears before it.
The query toolbox#
This test, from QueryTests.swift, uses every common way to narrow a query. The app is launched signed in with three tasks (chapter 6 shows how):
func testQueriesFindTheSeededTasks() throws {
// By accessibility identifier: every row shares "task.row".
let rows = app.buttons.matching(identifier: "task.row")
XCTAssertEqual(rows.count, 3)
// By label: the visible title.
XCTAssertTrue(app.buttons["Call Anna"].exists)
// By position: the first match of a query.
XCTAssertEqual(rows.firstMatch.label, "Buy milk")
XCTAssertEqual(rows.element(boundBy: 2).label, "Book flights")
// By predicate: anything whose label starts with "Book".
let book = app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Book"))
XCTAssertEqual(book.count, 1)
// Scoped: only text inside the navigation bar.
let title = app.navigationBars.staticTexts["Tasks"]
XCTAssertTrue(title.exists)
}
-
matching(identifier:)returns a query (many elements); subscripting returns one element. -
countresolves the query and counts matches. Use it to assert list sizes. -
firstMatchstops at the first match instead of resolving the whole tree, which is faster on big screens. Use it when you know there is exactly one, or when "any of them" is fine. -
element(boundBy:)picks by index in tree order. Fine for "the third row of a list I just seeded"; fragile for anything whose order you do not control. -
NSPredicatematches onidentifier,label,value,placeholderValue,elementType,isEnabled,isSelectedand more, withBEGINSWITH,CONTAINS,==and regular expressions viaMATCHES. -
Chaining (
app.navigationBars.staticTexts[...]) scopes the search to descendants of the first match, which avoids picking up an identical text somewhere else on the screen.
See what XCUITest sees#
When a query finds nothing, print the tree:
print(app.debugDescription)
An excerpt of the output for the task list with three seeded tasks (memory addresses and the plain Other wrappers SwiftUI adds are removed):
NavigationBar, {{0.0, 62.0}, {402.0, 54.0}}, identifier: 'Tasks'
StaticText, {{178.3, 73.7}, {45.3, 20.7}}, label: 'Tasks'
Button, {{295.0, 66.0}, {87.0, 36.0}}, identifier: 'tasks.signOut', label: 'Sign out'
TextField, {{16.0, 116.0}, {331.3, 34.0}}, identifier: 'tasks.newTitle', placeholderValue: 'New task'
Button, {{355.3, 122.7}, {30.7, 20.3}}, identifier: 'tasks.add', label: 'Add', Disabled
CollectionView, {{0.0, 160.7}, {402.0, 636.7}}, identifier: 'tasks.list'
Cell, {{16.0, 195.7}, {370.0, 52.0}}
Button, {{16.0, 195.7}, {370.0, 52.0}}, identifier: 'task.row', label: 'Buy milk', value: open
Image, {{33.3, 213.3}, {17.0, 17.0}}, identifier: 'circle', label: 'circle'
StaticText, {{59.7, 211.5}, {64.3, 20.3}}, label: 'Buy milk'
...
StaticText, {{174.5, 803.7}, {53.0, 20.3}}, identifier: 'tasks.count', label: '3 open'
Every line is type, frame, identifier, label, value and state. Notice that the row's title also exists as a StaticText inside the button: app.staticTexts["Buy milk"] and app.buttons["Buy milk"] are two different elements, and only the button carries the open/done value. It tells you at once whether the element exists under a different type, has no identifier, or is disabled. Two other tools show the same information interactively: Xcode's Accessibility Inspector (Xcode > Open Developer Tool) and a breakpoint in a test followed by po app.debugDescription in the debugger console.
app.buttons["task.row"].tap() fails with "Multiple matching elements found". What should the test do instead?
The query is ambiguous because all rows share the identifier, which is by design. Waiting does not change the number of matches, a different element type finds nothing, and random identifiers cannot be queried at all.
Next: tapping, typing, swiping, and asserting on what changed.