skip to content

A SwiftUI login view model's test checks the loading spinner state after Task.sleep and fails intermittently on CI; how do you make that async test deterministic?

level: seniorimportance: should knowfreq 55%

answer

  1. sleeping is guessing at a race
  2. await the work, do not wait for it
  3. who owns the Task
  4. a fake the test can hold open

basics

~20 s

Make signIn() async so the test awaits the whole flow instead of sleeping. For the in-flight spinner, use a fake service that signals when called and suspends until the test releases it, and assert isLoading in between.

solid answer

~40 s

A sleep only guesses how long the work takes, so on a loaded CI machine it loses the race. First, stop the model from spawning fire-and-forget work: `signIn()` is `async`, and the view owns the `Task` (`Button("Sign In") { Task { await model.signIn() } }`), so a test can `await model.signIn()` and read the end state with no waiting. Second, for the intermediate state, use a gated fake: its `signIn` signals "I was called" through an `AsyncStream` and then suspends until the test yields a reply. The test starts the call in a `Task`, awaits the signal, asserts `isLoading == true`, yields the reply, awaits the task's `value` and asserts the final state. Every step waits on an event, not on a clock.

code

swift · 17 lines
swift
final class GatedAuth: AuthService {
    let calls: AsyncStream<Void>
    private let callsIn: AsyncStream<Void>.Continuation
    private let replies: AsyncStream<Result<User, AuthError>>
    let reply: AsyncStream<Result<User, AuthError>>.Continuation

    init() {
        (calls, callsIn) = AsyncStream.makeStream()
        (replies, reply) = AsyncStream.makeStream()
    }

    func signIn(email: String, password: String) async throws -> User {
        callsIn.yield()
        for await result in replies { return try result.get() }
        throw CancellationError()
    }
}

go deeper

for a junior

Recall that sleeping in a test guesses at timing; the fix is to await the work itself.

for a middle

Explain why an async signIn() owned by the view's Task is awaitable while a fire-and-forget Task inside the model is not.

for a senior

Build the gated fake on the spot, explain why waiting on its call announcement makes the isLoading assertion deterministic, and use it to expose the cancellation bug.

for a principal

Make no sleeps in unit tests a review rule, and require models to expose or own their tasks in ways a test can await.

## Why the sleep-based test flakes A typical flaky test looks like this: call `model.submit()`, `try await Task.sleep(for: .milliseconds(100))`, then assert `model.user != nil`. It passes on a fast laptop and fails on a busy CI runner, because the sleep is a **guess** about how long the work takes. Two design choices in the model usually force that guess: - **Fire-and-forget work.** `func submit() { Task { await signIn() } }` returns before anything happens. The test has no handle to wait on. A quick check confirms it: right after `submit()` the model's `user` is still `nil`, because the spawned task has not run. - **No control over the service.** With a fake that answers instantly, the loading state may already be gone by the time the test looks; with a real client, the timing depends on the network. ## Step 1: make the flow awaitable Keep the model's action `async` and let the **view** own the task: - the model exposes `func signIn() async`; - the button calls `Task { await model.signIn() }`, or the screen uses `.task` when loading should start on appearance (its automatic cancellation is covered in the lesson on appearance and async work); - the test calls `await model.signIn()` and, when it resumes, every state change in the flow has happened. If the model really must start work itself (a debounce, a refresh timer), have it store the `Task` in a property or return it, so a test can `await task.value`. ## Step 2: hold the fake open to see the middle The end state is easy once the flow is awaitable. The **spinner state** only exists while the request is in flight, so the test must control when the request finishes. A gated fake does that with two `AsyncStream`s made with `AsyncStream.makeStream()`: 1. **calls**: the fake yields into it the moment `signIn` is entered. At that point the model has already set `isLoading = true` and is suspended awaiting the service. 2. **replies**: the fake suspends in `for await` on this stream until the test yields a `Result`. The test then runs a fixed sequence: 1. start `let signIn = Task { await model.signIn() }` (the task inherits the test's main actor); 2. `for await _ in auth.calls { break }` to wait until the request is in flight; 3. `#expect(model.isLoading)`; 4. `auth.reply.yield(.success(User(name: "Ada")))`; 5. `await signIn.value`, then assert `isLoading == false` and the user. Every wait is on an **event** the code produces, so the test passes or fails the same way on every machine. Two details make this safe. `AsyncStream.makeStream()` buffers without limit by default, so if the fake yields its announcement before the test starts iterating `calls`, the value waits in the buffer instead of being lost. And because the model is suspended on the service, nothing else can change `isLoading` between the announcement and the assertion: the next change happens only when the test yields a reply. ## Choosing a technique | Situation | Technique | |---|---| | Only the end state matters | `await model.signIn()` with an instant stub | | The in-flight state matters | gated fake: signal on call, release on demand | | The model starts its own work | store or return the `Task`, then `await task.value` | | The result arrives through a callback | the test framework's own confirmation helpers | | Debounced input | inject the delay or the clock rather than sleeping past it | ## Cancellation is part of the async state A gated fake also tests what happens when the user leaves mid-request. Cancel the task while the fake is suspended: the `for await` loop ends, the fake throws `CancellationError`, and the model's `catch` runs. A model that maps every error to "Email or password is wrong." now shows that message for a screen the user already left, which is a real bug the test exposes. The fix is to handle `CancellationError` separately and leave `errorMessage` untouched. ## What does not fix it - A longer sleep: the test gets slower and still flakes under enough load. - `await Task.yield()` once and hoping the task has run: ordering of queued main-actor work is not a contract the test should depend on. - Disabling the test on CI: the race in the design is still there.

  • Why not assert isLoading right after creating the Task, without the calls stream?
    Because nothing guarantees the task has started yet. The test is still running on the main actor, and the task's first step is queued behind it, so `isLoading` still reads `false` at that point. Waiting on the fake's call announcement ties the assertion to the moment the model has set `isLoading` and is suspended on the service.
  • The model uses Task internally to debounce typing. How do you test it without sleeping?
    Keep the debounce delay injectable and store the pending `Task` in a property the test can await. The test sets the delay to zero or near zero, types, then awaits the stored task's `value` before asserting. The point is that the test waits on the work, not on the clock.
  • What should the model do when the sign-in task is cancelled?
    Treat `CancellationError` as its own case: stop loading and leave `errorMessage` as it was, because the user did not get a wrong password, they left. A gated fake makes this testable by cancelling the task while the fake is suspended.

  • Add a longer sleep on CI so the async work has time to finish
  • A single Task.yield() guarantees the spawned task has run
  • The model should start its own Task so the view stays simple
  • The loading state cannot be unit tested, only seen in the UI
  • Every error from the service can map to the same user message