When you add time-based asynchrony to a Swift feature, good luck testing it! You’re often led to literal Task.sleeps in your suite, making it slow and flakey all at once.

But did you know it’s possible to make Task.sleep completely synchronous, without a single thread hop?

See how a “nonisolated(nonsending)” clock can make asynchronous work like Task.sleep completely synchronous: pointfree.co/episodes/ep355-be

A code snippet:

@MainActor @Observable final class OnboardingModel {
  var isOnboardingVisible = false
  private var clock: any NonsendingClock<Duration> = .continuous

  func onAppear() async throws {
    try await Task.sleep(for: .seconds(1), clock: clock)
    isOnboardingVisible = true
  }
}

@Test func basics() async throws {
  let model = OnboardingModel(clock: .immediate)
  try await model.onAppear()
  #expect(model.isOnboardingVisible)
}
// Test run with 1000 tests in 1000 suites passed after 0.566 seconds.
0

If you have a fediverse account, you can quote this note from your own instance. Search https://hachyderm.io/users/pointfreeco/statuses/116138095921253718 on your instance and quote it. (Note that quoting is not supported in Mastodon.)