Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created November 9, 2024 17:48
Show Gist options
  • Save robertmryan/889c68fa5fdec028b323e337e8a74ac5 to your computer and use it in GitHub Desktop.
Save robertmryan/889c68fa5fdec028b323e337e8a74ac5 to your computer and use it in GitHub Desktop.
final class MyAppTests: XCTestCase {
var cancellables: Set<AnyCancellable> = []
func testDemoDataIncorrect() {
let start = Date.now
// fire an event in 1 second, but only get the first value
let publisher = Timer.publish(every: 1, on: .main, in: .default)
.autoconnect()
.first()
publisher.sink { result in
if case .failure(let error) = result {
XCTAssert(true, "\(error)")
}
} receiveValue: { date in
XCTAssertLessThan(date, start) // should be XCTAssertGreaterThan(response, start)
}
.store(in: &cancellables)
}
func testDemoData() {
let start = Date.now
let expectation = expectation(description: "timer should fire")
let publisher = Timer.publish(every: 1, on: .main, in: .default)
.autoconnect()
.first()
.eraseToAnyPublisher()
publisher.sink { result in
if case .failure(let error) = result {
XCTAssert(true, "\(error)")
}
expectation.fulfill()
} receiveValue: { date in
XCTAssertGreaterThan(date, start)
}
.store(in: &cancellables)
waitForExpectations(timeout: 4)
}
}
@robertmryan
Copy link
Author

robertmryan commented Nov 9, 2024

A few changes from the original example:

  1. Rather than Just, I use a Timer.TimerPublisher to consistently manifest the scenario where a publisher publishes a value after you have already returned from testDemoDataIncorrect.

  2. An expectation can be used to make sure you don't return from testDemoData before the value is published.

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