Five XCUITest Failures a Longer Timeout Would Not Have Fixed (SwiftUI)

The CI log said the element was found two seconds into a fifteen-second wait. The test failed anyway.
A UI test that is green on my Mac and red on CI looks like a slow runner, and the obvious fix is a longer waitForExistence.
In FocusStudy, my own SwiftUI focus timer, I had five such failures between October 31 and November 10.
In none of them would a longer wait have been enough by itself.
Two were queries that matched a different element, two were fixtures whose timing was shorter than one accessibility query on CI, and one depended on the time of day.
Everything below was observed in one app.
CI runs the UI tests on a macos-26 runner with Xcode 26.6 and an iOS 26.5 iPhone simulator, pinned in the workflow.
When the first failure happened, my local simulator was iOS 27.1.
I describe what each runtime did for this app, not what SwiftUI guarantees.
1. firstMatch returned the Label's icon
The completion screen is one Label with one identifier:
Label("\(completedMinutes)분 집중을 마쳤어요", systemImage: "checkmark.circle.fill")
.accessibilityIdentifier("completion")
The Korean copy reads "You finished N minutes of focus". The test started a 40-minute session and checked that the copy said 40. It passed locally, and two CI runs on the branch failed. This is the second one, run 41211058575:
t = 5.21s Waiting 15.0s for "completion" Any to exist
t = 7.23s Checking existence of `"completion" Any`
t = 7.29s Find the "completion" Any
FocusFlowTests.swift:47: error: -[FocusUITests.FocusFlowTests testCompletionCopyUsesSessionLength] : XCTAssertTrue failed
t = 8.57s Find the "completion" Image
The element existed two seconds into a fifteen-second wait, so time was not the issue.
The last line names the reason: the element that matched was an Image.
On the iOS 26.5 simulator, the Label exposed its icon and its text under the same identifier, and the icon came first, with the label "Selected".
The assertion read "Selected" and looked for "40분".
I do not know why the order differs between the two runtimes.
The fix selects by identifier and label together, and prints the label it read:
// before
let completion = app.descendants(matching: .any).matching(identifier: "completion").firstMatch
XCTAssertTrue(completion.label.contains("40분"))
// after
let completion = app.descendants(matching: .any).matching(NSPredicate(format: "identifier == 'completion' AND label CONTAINS '집중을 마쳤어요'")).firstMatch
XCTAssertTrue(completion.label.contains("40분"), completion.label)
The second argument matters as much as the predicate.
The original failure said only XCTAssertTrue failed; with the label as the message, it would have said "Selected".
2. A container identifier replaced its rows' identifiers
On November 6 I added a collapsible "saved schedule" list.
The first version put an identifier on the DisclosureGroup and separate identifiers on each row inside it.
By then I ran UI tests on a local iOS 26.5 simulator too, so this one never reached CI.
The disclosure opened and the rows rendered, but the row queries found nothing.
The hierarchy dump showed why:
Button, identifier: 'everydayStoredSchedule', label: '저장된 일정'
StaticText, identifier: 'everydayStoredSchedule', label: '08:00부터 12:00까지, 제한'
StaticText, identifier: 'everydayStoredSchedule', label: '12:00부터 13:00까지, 해제'
StaticText, identifier: 'everydayStoredSchedule', label: '13:00부터 18:00까지, 제한'
Each row carried the container's identifier instead of its own everydayStoredSegment.N.
A wait of any length returns the same answer, because the identifier the test asks for is not in the tree.
In the version that merged, the container has no identifier, the rows keep theirs, and the test opens the disclosure by its visible label:
let stored = app.buttons["저장된 일정"]
scrollEveryday(app, to: stored); stored.tap()
let storedFirst = app.staticTexts["everydayStoredSegment.1"]
The same test attaches the hierarchy to every run, which is the reusable part:
let hierarchy = XCTAttachment(string: app.debugDescription)
hierarchy.name = "everyday-preview-accessibility"; hierarchy.lifetime = .keepAlways; add(hierarchy)
I saw this on an iPhone 17 simulator with iOS 26.5 and Xcode 26.6. I did not test other containers or other OS versions.
3. A two-second state ended between two property reads
The next two cases are about time, but not about a wait that was too short. Tapping "take a break" shows a progress message and disables the buttons. A DEBUG launch argument held that state for two seconds so that a test could read it. On CI (run 42450796120):
t = 9.73s Synthesize event
t = 10.71s Waiting 5.0s for Any (First Match) to exist
t = 11.79s Checking existence of `Any (First Match)`
t = 11.95s Find the "breakStart" Button
t = 12.14s Find the "end" Button
FocusFlowTests.swift:175: error: -[FocusUITests.FocusFlowTests testSlowBreakRequestAndReturnShowProgressAndDisableActions] : XCTAssertFalse failed
The progress message was found about two seconds after the tap, so the wait succeeded.
Line 175 then read isEnabled on two buttons, and each read is another round trip to the app.
The two-second state had ended by then, and the test read the next screen's enabled button.
The fix for this test changed the fixture, not its timeout (the same commit also raised one wait in a sibling test):
- services.fixtureBreakHold = min(requested, 3)
+ services.fixtureBreakHold = min(requested, 5)
- let app = app(extra: ["--break-delay", "2"])
+ let app = app(extra: ["--break-delay", "5"])
A state that a test must observe has to outlast the poll that finds it and every read that follows. On this runner the existence check ran about once per second.
4. A slow query and the app's own timer
Other break tests used a short timing: a one-second wait before the break starts by itself, a three-second break, and a two-second grace after which a late start is refused. After the pull request that contained the previous fix, one of them failed in two of four CI runs. In one run the break was tapped at t = 36.83 s, an existence check began at 38.98 s, and the next step began at 41.67 s. The final hierarchy showed the focus screen with "쉬는 시간 3번 남았어요" (three breaks left): the break had never started.
My diagnosis in the fix PR was that the query occupies the app's main thread, so the app's timer tick is late as well. On that reading, the tick arrived after the grace and the session engine refused the start, which is its rule for a stale wait. I did not profile the runner, and there is no app log from the failed runs. What I did was inject a main-thread stall locally, and the old values failed in the same positions. If the diagnosis is right, the app was correct, the test was correct, and the fixture assumed that one second on the test's side is one second on the app's side.
- timing = BreakTiming(waits: [1, 2, 4], breakLength: 3, slack: 5, staleWaitGrace: 2)
+ timing = BreakTiming(waits: [1, 2, 4], breakLength: 3, slack: 15, staleWaitGrace: BreakTiming.standard.staleWaitGrace)
The standard grace is ten seconds.
The same commit also raised several waits in these tests, for example waitForExistence from 5 to 15 seconds, so I cannot credit the fixture change alone.
What a longer wait cannot do is make the app accept a start it has already refused.
Because a three-second break can also pass inside one query, the short-timing tests now accept either proof that it started:
private func breakStarted(_ app: XCUIApplication) -> XCUIElement {
app.descendants(matching: .any).matching(NSPredicate(format: "identifier IN %@", ["breakCountdown", "deadlineNotice"])).firstMatch
}
On that commit the UI job passed three times in a row, after a first attempt that failed in an unrelated history test. The next day a pull request that changed only documentation failed the same test (run 42767231688):
t = 114.01s Synthesize event
t = 119.29s Checking existence of `Any (First Match)`
t = 130.19s Capturing element debug description
One existence check took 10.9 seconds, against a one-second wait plus a ten-second grace.
5. The fixture started yesterday's session
The last one failed on my own Mac, on a local iOS 27.2 simulator, and only for a while. Two tests failed in a suite that started at 00:10 local time on November 5, one of them with this message:
XCTAssertEqual failed: ("오늘 집중 0분 · 0회") is not equal to ("오늘 집중 25분 · 1회")
The summary said "0 minutes, 0 sessions today" where the test expected one 25-minute session. The same build passed all 32 UI tests in a run that started at 00:26, with no change to the code. The fixture that produces a just-finished session backdates it:
let length = services.settings.lengthSeconds
_ = try services.engine.start(now: Date().addingTimeInterval(-(length - 3)), length: length, authorized: { .approved }, apply: {}, matches: { true })
With the default length of 25 minutes, a run in the first 25 minutes after midnight creates a session that started yesterday.
The history query filters on startedAt inside the requested day, and the app assigns a session that crosses midnight to its start day on purpose.
So the app was right and "today" was empty.
Two changes followed.
History-presentation tests got a separate fixture that seeds records inside today:
let now = Date(), start = max(Calendar.current.startOfDay(for: now), now.addingTimeInterval(-7200))
That did not repair the two tests that had failed, because they need the backdated session. Five days later a second fix launched them in a time zone where it is always just after noon:
private func noonZone() -> [String: String] {
let seconds = Int(Date().timeIntervalSince1970) % 86_400, lateHalf = seconds % 3600 >= 1800
return ["TZ": TimeZone(secondsFromGMT: (12 - seconds / 3600) * 3600 - (lateHalf ? 1800 : 0))!.identifier]
}
- let app = app("expiring")
+ let app = app("expiring", environment: noonZone())
The backdated fixture itself is unchanged; the two tests no longer launch it near midnight.
What I check before I touch a timeout
- Did the wait itself fail? If the log shows the element was found and a later line failed, more time cannot help (cases 1 and 3).
- Which element matched? Put the value you read into the assertion message, and attach
app.debugDescription. Select by identifier and label when an identifier can belong to more than one element (cases 1 and 2). - Does the fixture depend on a clock? A timed state must outlast the poll and the reads after it, and a backdated date must stay in the day the test asserts on (cases 3 and 5).
- Does the app's timer have to fire while the test is querying? Then the test's clock and the app's clock are not independent (case 4).
- Is the test hiding an app difference? One of my tests tapped outside a
confirmationDialogwhen its cancel button was absent, so it stayed green while a discard confirmation showed no keep-editing action. Requiring the button made it fail, and those confirmations are alerts now. - Only then: is it a precondition wait (element exists, is hittable) that timed out while later steps passed? Those I do route through one shared 30-second
readytimeout.
The decision I am least sure about
After the 10.9-second query I did not raise the grace again. A longer grace only moves the threshold, and the fixture would still depend on an app timer firing during a query. The alternative is a fixture that starts the break when the wait screen appears, without the timer. I have not built it: the issue stays open and records each recurrence, and until then a failure costs one rerun.
The strongest argument against my position is the cost of that rerun. The UI job takes about 26 minutes, and a check that fails for a known reason teaches me to rerun without reading the log, which is how the first failure in this article went unread twice. The argument for waiting is that the deterministic fixture would stop exercising the timer path that the test exists to cover.
Limits
This is one app, between October 31 and November 10, 2026.
Cases 1 to 4 are from the iOS 26.5 simulator with Xcode 26.6; case 5 first failed on a local iOS 27.2 simulator with Xcode 27.2.
I have the iOS 26.5 hierarchy dump for case 2 only.
For case 1 the CI log shows that the match was an Image; the "Selected" label and the local iOS 27.1 pass come from my pull-request notes, and I did not capture either hierarchy, so "the order differs" rests on the test passing there.
The claim that queries delay the app's timers rests on the CI timestamps and a local injected stall, not on a trace of the runner.
Several failures in the same period stayed unexplained: a launch that errored with Failed to terminate kr.donminzzi.focusStudy and passed on rerun, an unrelated bottom-sheet test that failed once and passed on rerun with the same code, and a gap of about seven and a half minutes before the UI suite started in one run.
I did not attribute those to anything, and they are the reason the checklist ends with a question and not a rule.
Get the next post.
Follow new posts in your RSS reader.