Test Async Swift Code Without Sleeping
An async test starts a task, sleeps for 100 milliseconds, and checks that a spinner is showing. It passes locally. Then CI gets busy, and the same test decides the spinner never appeared.
Increasing the sleep to a second makes the suite slower without establishing the fact we actually care about: did the request reach the loading boundary?
Let’s make that boundary observable. Our test will wait for the request to start, inspect the intermediate state, and release the result itself. The scheduler can take as long as it needs between those steps.
Keep the feature small enough to control
Here is the model we want to test:
@MainActor
final class LoadingModel {
enum State: Equatable {
case idle, loading
case loaded(String)
case failed
}
private(set) var state = State.idle
private let fetch: @Sendable () async throws -> String
init(fetch: @escaping @Sendable () async throws -> String) {
self.fetch = fetch
}
func load() async {
state = .loading
do { state = .loaded(try await fetch()) } catch { state = .failed }
}
}
The model accepts an async dependency. Production can supply a repository or API client. The test can supply a response that remains suspended until we release it.
This model intentionally has one loading operation. Cancellation UI, overlapping searches, and retries need their own policies; they should not be hidden inside a testing trick. Here we are proving the transition from loading to a single result.
If all we wanted was the final state, we could simply await model.load() and assert afterward. The controlled response earns its place because we also want to inspect the model during the request.
Build a one-request gate
This fixture uses continuations to expose two explicit milestones: the request has entered the dependency, and the test has supplied its response.
actor SuspendedResponse {
private var response: CheckedContinuation<String, Error>?
private var started = false
private var startWaiters: [CheckedContinuation<Void, Never>] = []
func fetch() async throws -> String {
precondition(!started, "This fixture supports one request")
return try await withCheckedThrowingContinuation { continuation in
response = continuation
started = true
let waiters = startWaiters
startWaiters.removeAll()
for waiter in waiters { waiter.resume() }
}
}
func waitUntilStarted() async {
if started { return }
await withCheckedContinuation { startWaiters.append($0) }
}
func complete(_ result: Result<String, Error>) {
precondition(
response != nil,
"Start the request before completing it")
let continuation = response!
response = nil
continuation.resume(with: result)
}
}
The actor protects the fixture’s bookkeeping. waitUntilStarted() works whether the test gets there before or after fetch() starts. We do not need to predict which task the executor chooses first.
The stored continuation is cleared before it is resumed. An accidental second completion then fails loudly instead of resuming the same continuation twice.
There is an important ownership rule: this is a test fixture, and the test must always supply a result. Canceling a task alone does not automatically resume a checked continuation. Do not copy this into a production callback adapter without designing cancellation and teardown for that real API.
Assert while the response is suspended
Now the test can express the order it needs:
import Testing
@Test(.timeLimit(.minutes(1))) @MainActor
func loadingThenSuccess() async {
let response = SuspendedResponse()
let model = LoadingModel { try await response.fetch() }
let operation = Task { await model.load() }
await response.waitUntilStarted()
#expect(model.state == .loading)
await response.complete(.success("Loaded book"))
await operation.value
#expect(model.state == .loaded("Loaded book"))
}
Once waitUntilStarted() returns, the model has already assigned .loading and entered its dependency. That dependency cannot finish until the test calls complete. Our intermediate assertion therefore has a real ordering guarantee.
The final assertion waits for the model operation, not merely the response gate. Resuming the dependency makes progress possible; it does not mean the model has already resumed and stored its new state.
The time limit is a diagnostic backstop. It is not how we synchronize the test, and it cannot magically make a broken, non-cooperative continuation finish. Keep a process-level timeout in CI for tests that can hang because of implementation bugs.
#expect records a failure and lets execution continue, so the fixture still receives its result if the loading assertion fails. If you introduce a throwing #require before completion, arrange cleanup so that failure cannot leave the operation suspended forever.
To test failure, use the same ordering and complete with an error:
enum FixtureError: Error { case unavailable }
@Test(.timeLimit(.minutes(1))) @MainActor
func loadingThenFailure() async {
let response = SuspendedResponse()
let model = LoadingModel { try await response.fetch() }
let operation = Task { await model.load() }
await response.waitUntilStarted()
#expect(model.state == .loading)
await response.complete(.failure(FixtureError.unavailable))
await operation.value
#expect(model.state == .failed)
}
Create a new fixture and model for that test. The fixture deliberately supports one response, making accidental reuse easy to spot.
A confirmation is a count check, not a wait command
Swift Testing’s confirmation is useful when an operation should report a certain number of events. Keep the operation alive inside the confirmation’s closure:
func importBooks(didImport: @Sendable (String) -> Void) async {
didImport("A")
didImport("B")
}
@Test
func confirmsImportedBooks() async {
await confirmation("Imported books", expectedCount: 2) { imported in
await importBooks { _ in imported() }
}
}
Apple’s Swift Testing migration guide explains that confirmations check occurrences within the supplied body. Launching an unstructured task and immediately returning from that body can make the check happen before the callbacks run. Await the operation or bridge its completion explicitly.
Similarly, Task.yield() offers another task an opportunity to run. It is not evidence that a particular dependency started. A test that needs that fact should wait for a signal representing that fact.
Keep real timing tests separate
Some features really do have temporal behavior: a debounce interval, an expiration deadline, or a retry backoff. For those, inject a clock or scheduler and advance controlled time. A response gate tests request ordering; it does not test elapsed-time semantics.
That separation makes failures easier to understand. “The spinner never entered loading” and “the debounce fired before its deadline” should be different tests with different controls.
September 2026 review: the complete Swift package for this article was checked with Swift 6.4 and Xcode 27. It includes loading-to-success, loading-to-failure, and two-callback confirmation cases. None of those tests depends on a sleep or an external service.
When an async test flakes, I first look for an assumption about when another task should have run. Replacing that assumption with one explicit milestone often removes both the flake and the unnecessary waiting.