Exit course
Chapter 5 of 11 Intermediate 7 min read 2 quick checks Updated

Waiting Without sleep(): waitForExistence and Predicates

On this page
  1. Why not sleep()
  2. waitForExistence(timeout:)
  3. Waiting for anything else: XCTNSPredicateExpectation
  4. A real flake: the sheet that eats a tap

XCUITest waits for the app to be idle before every query and action. That covers animations and work on the main thread, and it is why the tests so far needed no waits. It does not cover work the app has not started yet or is doing elsewhere: a network call that answers in two seconds, a timer, a system sheet that slides in after a screen changed. For those you wait for a condition, never for a fixed time.

Why not sleep()#

sleep(3) before an assertion has two failure modes and no upside. When the app is faster than three seconds, every run wastes the difference; across a few hundred tests that is the bulk of a CI job. When the app is slower (a cold simulator, a busy CI machine, a real device on a slower network), the test fails anyway. A condition-based wait returns the moment the condition holds and only fails when it truly does not happen within a generous limit. The Flaky Tests course covers this class of problem in general; this chapter is the XCUITest toolkit.

waitForExistence(timeout:)#

The Tasks sign-in calls a pretend server that answers after about two seconds. This test fills in the form and waits for the task list:

import XCTest

final class LoginWaitTests: XCTestCase {
    let app = XCUIApplication()

    override func setUpWithError() throws {
        continueAfterFailure = false
        app.launchArguments = ["-resetState"]
        app.launch()
    }

    private func signIn(password: String) {
        let email = app.textFields["login.email"]
        email.tap()
        email.typeText("anna@example.com")
        let pass = app.secureTextFields["login.password"]
        pass.tap()
        pass.typeText(password)
        app.buttons["login.submit"].tap()
    }

    func testSignInWaitsForTheTaskList() throws {
        signIn(password: "secret")

        // The login call takes about two seconds. Wait for the result, not for a fixed time.
        let title = app.navigationBars["Tasks"]
        XCTAssertTrue(title.waitForExistence(timeout: 10), "Task list did not appear")
    }
}

waitForExistence(timeout:) polls until the element exists and returns true, or returns false after the timeout. It does not fail the test by itself, which is why it sits inside XCTAssertTrue with a message. The timeout is an upper bound, not a delay: the run log shows the wait ending as soon as the navigation bar appeared, about two seconds in.

Pick timeouts by asking "after how long is this certainly broken?", not "how long does it usually take?". Ten seconds for a two-second call is reasonable. Real devices and CI simulators are slower than your laptop.

Waiting for anything else: XCTNSPredicateExpectation#

waitForExistence only answers one question. For "this has disappeared", "this became enabled" or "this label changed", use an expectation with a predicate on the element:

func testWrongPasswordShowsAnErrorAfterTheSpinnerGoes() throws {
    signIn(password: "wrong")

    let spinner = app.activityIndicators["login.spinner"]
    let gone = XCTNSPredicateExpectation(
        predicate: NSPredicate(format: "exists == false"),
        object: spinner
    )
    XCTAssertEqual(XCTWaiter().wait(for: [gone], timeout: 10), .completed)

    let error = app.staticTexts["login.error"]
    XCTAssertTrue(error.exists)
    XCTAssertEqual(error.label, "Wrong email or password")
}

The predicate is evaluated against the element repeatedly until it holds. Any property from chapter 3 works: isEnabled == true, isHittable == true, label == "3 open", value == "done". XCTWaiter().wait(for:timeout:) returns a result (.completed, .timedOut, ...) that you assert on; the alternative, wait(for: [gone], timeout: 10) inside the test case, fails the test directly on timeout.

Recent Xcode versions also have shorter forms, both of which passed on the Xcode 26.4.1 used for this course:

XCTAssertTrue(app.activityIndicators["login.spinner"].waitForNonExistence(timeout: 10))
XCTAssertTrue(app.staticTexts["login.error"]
    .wait(for: \.label, toEqual: "Wrong email or password", timeout: 5))

Use them if your team's oldest supported Xcode has them; the predicate version works everywhere.

A test asserts XCTAssertFalse(app.activityIndicators["loading"].exists) right after tapping Refresh, and it passes even when loading never finishes. Why?

A one-shot check of a negative is the classic false pass. Wait for the positive outcome instead (the refreshed content exists), or first wait for the spinner to appear and then for it to disappear.

A real flake: the sheet that eats a tap#

While writing chapter 5, a test that signs in and then adds two tasks failed in most runs on the iOS 26.4 simulator. The failure moved around: sometimes "Neither element nor any descendant has keyboard focus" when typing the first task, sometimes the second task was simply missing. The same steps passed when the app was launched directly on the task list.

A screenshot taken inside the test, right after the list appeared, showed the cause: iOS's Save Password? sheet, which the system offers after a successful sign-in with a password field. It slides in after the new screen is already showing and swallows the next tap. The element tree had it inside the app, so the test can deal with it like any other element.

The first fix waited for the sheet, tapped "Not Now" and then waited for the sheet to be gone before going on, because without that second wait the run log showed the next tap computing a hit point of {-1, -1}: the field was still covered by the sheet's dismiss animation. That version passed three runs out of three on the iOS 26.4 simulator and on two real iPhones.

Then the suite ran on an iOS 27 simulator, and the "wait until gone" timed out. The run log explained it: the test found "Not Now" 0.6 seconds after it appeared and tapped it while the sheet was still sliding in. The tap missed, and the sheet stayed. The version in the course now handles both cases:

// After a successful sign-in iOS may offer to save the password.
// The sheet sits on top of the list and swallows the next tap.
// A tap while it is still sliding in can miss, so tap until it is gone.
let notNow = app.buttons["Not Now"]
if notNow.waitForExistence(timeout: 3) {
    for _ in 0..<3 where notNow.exists {
        notNow.tap()
        _ = notNow.waitForNonExistence(timeout: 3)
    }
    XCTAssertFalse(notNow.exists, "The Save Password sheet did not go away")
}

Three waits, each with a reason. The first gives the sheet up to three seconds to show up (whether the system offers to save a password depends on the device and its settings, so the whole block is optional). The loop taps and then waits for the sheet to leave; if a tap was lost to the animation, it taps again, at most three times. The final assertion makes a sheet that never goes away fail here, with a clear message, instead of three steps later with a confusing one. With this version the whole suite passed twice in a row on both the iOS 26.4 and the iOS 27 simulator.

The general lessons: when a failure moves around, take a screenshot (XCUIScreen.main.screenshot()) or print the tree at the moment it fails; and when something appears on its own schedule, wait for it to appear and to go away.

For system permission alerts (camera, location, notifications), XCTest also has addUIInterruptionMonitor(withDescription:handler:), a handler that runs when an alert blocks the next interaction. It is worth knowing about, but an explicit wait-and-tap like the one above is easier to reason about when you know which dialog to expect. Chapter 6 shows the third option: configure the app so the dialog never appears.

An optional dialog appears sometimes after login. Which handling keeps the test both reliable and fast?

A short bounded wait costs at most a few seconds when the dialog is absent and returns at once when it shows up. Tapping a missing element fails the test, a fixed sleep is slow and still racy, and a 30-second wait makes every run without the dialog 30 seconds slower.

Next: the sign-in steps now appear in three test files. Time to put them in one place.