Skip to content

Instantly share code, notes, and snippets.

@yannxou
Last active November 28, 2024 08:18
Show Gist options
  • Save yannxou/16d5c11bf6cb686e716390d51746c386 to your computer and use it in GitHub Desktop.
Save yannxou/16d5c11bf6cb686e716390d51746c386 to your computer and use it in GitHub Desktop.
Publisher value expectation for swift-testing
import Combine
import Foundation
public extension Publisher {
func expect(performing action: @escaping () async -> Void, fulfills condition: @escaping (Output) -> Bool, timeout: TimeInterval) async -> Bool {
let publisher = self
.handleEvents(receiveSubscription: { _ in
Task {
await action()
}
})
.timeout(.seconds(timeout), scheduler: DispatchQueue.main)
do {
for try await value in publisher.values {
if condition(value) {
return true
}
}
} catch { }
return false
}
}
public extension Publisher where Output: Equatable {
func expect(performing action: @escaping () async -> Void, emits expectedValue: Output, timeout: TimeInterval) async -> Bool {
await expect(performing: action, fulfills: { $0 == expectedValue }, timeout: timeout)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment