Last active
March 2, 2023 17:47
-
-
Save woodycatliu/07f1ba08fd10a303e819157f8843c41e to your computer and use it in GitHub Desktop.
Easy to do Combine test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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