.agents/skills/swift-testing-expert/references/async-testing-and-waiting.md
Use this file when tests involve async/await functions, completion handlers, streams/events, or timing-related flakiness.
await naturally.import Testing
struct APIClient {
func fetchName() async throws -> String { "Antoine" }
}
@Test func fetchNameReturnsValue() async throws {
let client = APIClient()
let value = try await client.fetchName()
#expect(value == "Antoine")
}
withCheckedContinuationwithCheckedThrowingContinuationimport Testing
func legacyLoad(_ completion: @escaping (Result<Int, Error>) -> Void) {
completion(.success(42))
}
@Test func legacyAPI() async throws {
let value = try await withCheckedThrowingContinuation { continuation in
legacyLoad { result in
continuation.resume(with: result)
}
}
#expect(value == 42)
}
await.import Testing
@Test func eventIsPublishedTwice() async {
await confirmation("Publishes two events", expectedCount: 2) { confirm in
confirm()
confirm()
}
}
import Testing
actor EventCounter {
private(set) var count = 0
func increment() { count += 1 }
}
@Test func countEventsSafely() async {
let counter = EventCounter()
await counter.increment()
await counter.increment()
#expect(await counter.count == 2)
}
// Avoid this pattern:
// try await Task.sleep(nanoseconds: 500_000_000)
// #expect(flag == true)
@MainActor) only when behavior truly requires it.import Testing
@MainActor
@Test func uiModelMutation() {
#expect(true)
}