In XCUITest, why use waitForExistence(timeout:) instead of sleep, and why can an element that exists still fail isHittable?
answer
- a fixed pause versus a condition
- returns early, gives up at the timeout
- the result is a Bool to assert
- in the tree is not tappable
- offscreen or covered by another view
basics
~20 swaitForExistence(timeout:) returns true as soon as the element exists and false at the timeout, so a test waits only as long as it needs. exists means the element is in the UI tree; isHittable also needs it onscreen and not covered.
solid answer
~40 sA `sleep` pays the full delay on a fast run and still fails on a slow one. `waitForExistence(timeout:)` returns `true` the moment `exists` turns true, or `false` when the timeout expires. It does not fail the test itself, so wrap it in `XCTAssertTrue`; the compiler warns when the result is discarded. `waitForNonExistence(timeout:)` waits for a spinner to go, and in Xcode 27.1's SDK `wait(for:toEqual:timeout:)` waits for a key path such as `\.isEnabled`. `exists` means the element is in the app's current hierarchy. `isHittable` is true only when it can be tapped where it is now, so it is false offscreen or under another element. `tap()` still scrolls an offscreen element into view.
code
swift · 21 linesimport XCTest
final class PaymentWaitUITests: XCTestCase {
@MainActor
func testWaitsForPaymentToFinish() {
let app = XCUIApplication()
app.launch()
app.buttons["payButton"].tap()
// Returns as soon as the spinner is gone; false after 10 s.
let spinner = app.activityIndicators["paymentSpinner"]
XCTAssertTrue(spinner.waitForNonExistence(timeout: 10))
let receipt = app.staticTexts["receiptTotal"]
XCTAssertTrue(receipt.waitForExistence(timeout: 5))
let done = app.buttons["doneButton"]
XCTAssertTrue(done.wait(for: \.isEnabled, toEqual: true, timeout: 5))
done.tap()
}
}go deeper
Recall that waitForExistence(timeout:) returns a Bool you assert, and that a fixed sleep is the wrong tool.
Explain the four waits, their timeouts in seconds, and the difference between exists and isHittable, including the offscreen case.
Show where a suite really needs waits: after requests, navigation and dismissals, waiting on what a user sees and failing at that line.
Weigh per-step timeouts against one global value, and how you stop sleeps from creeping back into a shared suite.
## Why fixed sleeps fail A UI test races the app. After a tap, the app may load data, animate a sheet or wait for a network reply before the next element appears. The test runner is a separate process that sees the element tree, not your app's own work, such as a request still in flight. A fixed pause, `sleep(3)`, guesses. On a fast simulator it wastes three seconds per step. On a busy CI machine the reply takes four seconds and the test fails anyway. Across hundreds of steps you get a suite that is slow **and** flaky. ## The waiting APIs XCUITest gives you XCUITest's waits check a condition and return as soon as it holds: | API | Owner | Returns `true` when | |---|---|---| | `waitForExistence(timeout:)` | `XCUIElement` | `exists` becomes true | | `waitForNonExistence(timeout:)` | `XCUIElement` | `exists` becomes false | | `wait(for:toEqual:timeout:)` | `XCUIElement` | a key-path property equals a value | | `wait(for:timeout:)` | `XCUIApplication` | the app reaches an `XCUIApplication.State` | Each takes a timeout in **seconds** and returns a `Bool`. None of them fails the test by itself; it returns `false` when the timeout expires. That gives one trap: - `button.waitForExistence(timeout: 5)` on its own line throws the answer away. The Objective-C header marks it with a warn-unused attribute, so Swift reports *result of call to 'waitForExistence(timeout:)' is unused*. Write `XCTAssertTrue(button.waitForExistence(timeout: 5))` so a timeout becomes a failure at the line that waited. - `waitForNonExistence(timeout:)` carries no such mark, so discarding its result compiles **silently**. A spinner that never goes away then shows up as a confusing failure two steps later. Assert it the same way. `wait(for:toEqual:timeout:)` is in the Xcode 27.1 SDK. It is generic over `Equatable` values, so `wait(for: \.isEnabled, toEqual: true, timeout: 5)` waits for a Pay button that turns on only after a duration is chosen. Check that it exists in the Xcode version you build with before a team adopts it. ## exists versus isHittable Two properties answer two different questions: 1. **`exists`**: is the element in the app's current UI hierarchy? It can be true for something far below the fold or hidden under a sheet. 2. **`isHittable`**: can XCUITest compute a hit point to tap it **where it is now**? It is false when the element does not exist, is offscreen, or is covered by another element. Apple's documentation adds a detail people miss: `isHittable` is false for an offscreen element in a scrollable view **even though** `tap()` would scroll it into a hittable position first. So these rules follow: - Wait with `waitForExistence(timeout:)`, then act. Don't loop until `isHittable` turns true for a row that `tap()` would scroll to anyway. - Assert `isHittable` when the point *is* reachability: for example, that a modal overlay has really gone and the Pay button underneath can be tapped. - An element that exists but sits under a dismissing sheet is not hittable yet, so the tap may not land where you meant. Wait for the sheet with `waitForNonExistence(timeout:)` first. ## When an event method resolves the element An event such as `tap()` resolves its element at the moment it is called. If the query matches zero elements or more than one, an error is raised. So waiting is the test's job at every step where the app does asynchronous work: after a tap that triggers a request, after navigation, after a sheet dismisses. `launch()` and `activate()` are the exceptions you get for free; both return when the app is ready to handle events. ## Habits that keep waits honest - **Wait on the outcome a user would see**, such as the receipt total, not on an internal spinner alone. - **Pick timeouts per step.** A screen transition needs seconds; a payment against a slow stub needs more. - **Wait for disappearance** with `waitForNonExistence(timeout:)` before tapping something a sheet or spinner covers. - **Never mix** a sleep and a wait; the sleep only adds time. - **Check the app's state too.** After backgrounding or relaunching, `app.wait(for: .runningForeground, timeout:)` confirms the app is where the next step expects it. The general theory of flaky tests belongs to testing practice. What an interviewer checks here is that you know XCUITest's own tools: the four waits, their `Bool` results, and the gap between being in the tree and being tappable.
- A test asserts XCTAssertTrue(row.isHittable) on a row far down a list and fails, yet row.tap() works. Why?`isHittable` is true only when the element can be tapped at its current location. Offscreen in a scroll view it is false, even though `tap()` first tries to scroll the element onscreen. Assert `exists`, or wait for existence, before tapping; assert `isHittable` only when reachability right now is the point.
- Your UI test calls waitForExistence(timeout:) from an async test method and the Swift 6 build fails. Why?`XCUIElement` and `XCUIApplication` are main-actor isolated. From a nonisolated async method, calling them is a warning in the Swift 5 language mode and an error in Swift 6 mode. Mark the test method or class `@MainActor`, and the calls compile without an await.
A fixed sleep is like boiling an egg by setting a ten-minute timer every time; waiting for existence is like watching the pot and stopping when it boils, while still giving up if nothing happens in ten minutes.
- Adding sleep calls until the UI test stops failing
- Calling waitForExistence(timeout:) without asserting its result
- Believing waitForExistence fails the test by itself on timeout
- Treating exists as proof that the element can be tapped
- Thinking isHittable must be true before tap() can scroll to a row
- Assuming a discarded waitForNonExistence result always draws a warning
Assumes Xcode 27.1 with the XCUIAutomation framework; wait(for:toEqual:timeout:) is in that SDK, so check the Xcode your team builds with before relying on it.