Skip to content

Instantly share code, notes, and snippets.

@janodev
Last active May 16, 2025 17:13
Show Gist options
  • Select an option

  • Save janodev/32217b09f307da8c96e2cf629c31a8eb to your computer and use it in GitHub Desktop.

Select an option

Save janodev/32217b09f307da8c96e2cf629c31a8eb to your computer and use it in GitHub Desktop.
waitForExpectation
import Foundation
import Testing
func waitForExpectation(
timeout: Duration,
description: String,
fileID: String = #fileID,
filePath: String = #filePath,
line: Int = #line,
column: Int = #column,
_ expectation: @escaping () -> Bool
) async {
let startTime = ContinuousClock.now
var fulfilled = false
await confirmation(
"Waiting for expectation: \(description)",
expectedCount: 1,
sourceLocation: SourceLocation(fileID: fileID, filePath: filePath, line: line, column: column)
) { confirm in
while !fulfilled && ContinuousClock.now - startTime < timeout {
if expectation() {
fulfilled = true
confirm()
break
}
await Task.yield()
}
if !fulfilled {
Issue.record("Expectation not fulfilled within \(timeout) seconds: \(description)")
}
}
}
try await waitForExpectation(timeout: .milliseconds(100), description: "Successful load check") {
let isSuccess: Bool = ...
return isSuccess
}
@Alipacman
Copy link
Copy Markdown

Hey,
just stumbled upon this. You build this since Swift Testing does not support async code which is run in an own Task, right?

Example which works:

await confirmation { soldFood in
      FoodTruck.shared.eventHandler = { _ in
         confirmation()
      }
      **await** FoodTruck.shared.sell()
  }

Example which won't work:

await confirmation { soldFood in
      FoodTruck.shared.eventHandler = { _ in
         confirmation()
      }
      FoodTruck.shared.sell() <- Here is no await as the FoodTruck runs the async code in its own Task. 
  }

Even when using @Test(.timeout) it won't work, right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment