In XCUITest, how do you find a button by its accessibility identifier, tap it, and type text into a search field?
answer
- query from the XCUIApplication proxy
- type-named query, then a string subscript
- the subscript matches more than the identifier
- typeText needs keyboard focus first
- labels move with copy edits and localization
basics
~20 sQuery from the XCUIApplication proxy, such as app.buttons["payButton"], then call tap(). For typing, tap the field so it has keyboard focus, then call typeText(_:). Identifiers beat labels because they don't change when the visible text does.
solid answer
~40 sA UI test starts from `XCUIApplication()`, launches it, and builds queries such as `app.buttons["payButton"]` or `app.searchFields["zoneSearchField"]`. `buttons` is shorthand for `descendants(matching: .button)`, and the string subscript matches any identifying property: `identifier`, `title`, `label`, `value` or `placeholderValue`. The app sets the identifier: `accessibilityIdentifier` on a UIKit view (nil by default) or the `accessibilityIdentifier(_:)` modifier in SwiftUI. `tap()` taps a hittable point and first tries to scroll an offscreen element into view. `typeText(_:)` raises an error unless the element or a descendant has keyboard focus, so tap the field first. I prefer identifiers because a label follows copy edits and localization, while an identifier only changes when a developer changes it.
code
swift · 17 linesimport XCTest
final class ZoneSearchUITests: XCTestCase {
@MainActor
func testSearchesForParkingZone() {
let app = XCUIApplication()
app.launch()
let search = app.searchFields["zoneSearchField"]
XCTAssertTrue(search.waitForExistence(timeout: 5))
search.tap() // give the field keyboard focus
search.typeText("4021")
app.cells["zoneRow-4021"].tap()
XCTAssertTrue(app.buttons["startParkingButton"].waitForExistence(timeout: 5))
}
}go deeper
Recall the chain: XCUIApplication, a type-named query, a string subscript, then tap() or typeText(_:). Say where the identifier is set in the app.
Explain that the subscript matches identifier, title, label, value or placeholderValue, and that typing raises an error without keyboard focus.
Show the naming rule you would enforce for identifiers, unique per row and named for the role, so tests survive localization and redesigns.
Weigh the cost of identifiers as part of the app's code review against brittle label queries that break each time copy or language changes.
## The pieces of a first UI test An XCUITest test drives your app the way a person would, from outside it. The test is a method on an `XCTestCase` subclass in a UI test target, and it talks to the app through a few types from Apple's UI-automation framework: - **`XCUIApplication`** is a *proxy* for the app. `XCUIApplication()` refers to the app set as the UI test target's *Target Application*, and `launch()` starts it. - **`XCUIElementQuery`** describes how to find elements, for example "all buttons in the app". - **`XCUIElement`** is one element that a query resolves to. You tap it, type into it and read its attributes. Nothing is looked up when you build a query. An element is resolved when you use it: when you call an event method like `tap()`, or read a property like `exists`. ## Building the query `XCUIApplication` is itself an element, so it has the **type-named query properties**: `buttons`, `searchFields`, `textFields`, `cells`, `staticTexts` and dozens more. Each one is shorthand for `descendants(matching:)` with an element type, so `app.buttons` means "every button anywhere in the app's element tree". The **string subscript** narrows that query: `app.buttons["payButton"]` returns an element whose identifying properties match `"payButton"`. Apple's documentation lists those properties: `identifier`, `title`, `label`, `value` or `placeholderValue`. That breadth is handy when you are exploring, and it is also why identifiers are the safer thing to pass. | You match on | Set by | Changes when | |---|---|---| | `identifier` | the developer, in code | a developer renames it | | `label` | usually the visible text | copy is edited or the app is localized | | index in a list | the layout | rows are added, removed or reordered | ## Setting identifiers in the app The identifier lives in the app's code, not the test's. In UIKit it is the `accessibilityIdentifier` property, which is `nil` by default. In SwiftUI it is the `accessibilityIdentifier(_:)` modifier. A good identifier names the element's role (`payButton`, `zoneRow-4021`), not its looks. Xcode's UI recording often offers several queries for the same element; Apple's recording guide says to pick the one that best represents the element's meaning instead of, for example, its position in a list. ## Tapping and typing 1. **`tap()`** sends a tap to a hittable point computed for the element. If the element is inside a scroll view but offscreen, the framework first tries to scroll it onscreen. 2. **`typeText(_:)`** types a string into the element. The element or one of its descendants must have keyboard focus, or XCUITest raises an error. In practice you call `tap()` on the field first, which brings up the keyboard and gives it focus. 3. When an event method runs, the element is resolved. If the query matches **zero or several** elements, an error is raised, so an identifier that two views share breaks the test. A test like the one in the code example searches for a zone, taps its row and waits for the next screen. It never refers to a label, so translating the app or rewording a button does not break it. ## What tends to go wrong - **Querying by visible text.** `app.buttons["Pay"]` works until someone changes the copy to "Pay now" or runs the suite in another language. - **Typing without focus.** Calling `typeText(_:)` before the field has focus raises an error; XCUITest does not tap the field for you. - **Reusing one identifier.** Two cells both called `zoneRow` make the subscript ambiguous; add the zone number or another stable key. - **Using the wrong type.** A table row is a `cell`, not a `button`, so `app.buttons["zoneRow-4021"]` finds nothing even though the identifier is right. `debugDescription` on the app prints the element tree, with each element's type, when you are not sure. ## Why this matters at screening level Interviewers ask this because it shows whether you have written a UI test that survives a redesign. The answer they want has three parts: the query starts from the application proxy, the identifier comes from the app's code, and typing needs focus. Knowing that the subscript also matches labels and values explains why a test that "worked yesterday" can suddenly match the wrong element.
- The zone row has the identifier zoneRow-4021, but app.buttons["zoneRow-4021"] never exists. Why?The type-named query filters by element type before the subscript checks the identifier. A table or collection row is reported as a cell, so `app.buttons` never contains it. Query `app.cells["zoneRow-4021"]`, or `app.descendants(matching: .any)["zoneRow-4021"]` while exploring, and print `app.debugDescription` to see each element's type.
- How do you tap a spot on a map view that has no element of its own?Make a coordinate relative to an element that does exist: `app.maps.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()`. The offset is multiplied by the element's frame size and added to its origin, so 0.5, 0.5 is the centre. It is a last resort, because a coordinate breaks when the layout moves.
- Querying buttons by their visible title text in every test
- Believing the string subscript matches only the accessibility identifier
- Calling typeText(_:) without first giving the field keyboard focus
- Giving every row in a list the same identifier
- Thinking the test can set identifiers itself without app code changes