Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Last active March 2, 2023 17:47
Show Gist options
  • Save woodycatliu/07f1ba08fd10a303e819157f8843c41e to your computer and use it in GitHub Desktop.
Save woodycatliu/07f1ba08fd10a303e819157f8843c41e to your computer and use it in GitHub Desktop.
Easy to do Combine test
import Foundation
import Combine
import XCTest
extension XCTestCase {
func awaitPublisher<P: Publisher>(
_ publisher: P,
timeout: TimeInterval,
description: String,
trigger: (() -> Void)? = nil,
file: StaticString = #file,
line: UInt = #line
) throws -> P.Output {
var cancelable: AnyCancellable?
var result: Swift.Result<P.Output, P.Failure>?
let excep = expectation(description: description)
cancelable = publisher.first().sink(receiveCompletion: {
switch $0 {
case .failure(let error):
result = .failure(error)
case .finished: break
}
excep.fulfill()
}, receiveValue: {
result = .success($0)
})
trigger?()
wait(for: [excep], timeout: timeout)
cancelable?.cancel()
return try XCTUnwrap(result, "Awaited publisher did produce null output ",
file: file,
line: line).get()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment