Intermediate Combine

Apr 13 2021 · Swift 5.3, macOS 11.1, Xcode 12.2

Part 1: Intermediate Combine

06. Testing Combine Operators

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Retrying and Catching Errors Next episode: Part 1 Quiz: Intermediate Combine

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Testing is an important part of development for all apps. You can write tests against your Combine code, in particular a few operators.

var subscriptions = Set<AnyCancellable>()
  
  override func tearDown() {
    subscriptions = []
  }

  func test_collect() {
      // Given
      let values = [0, 1, 2]
      let publisher = values.publisher
      // When
      publisher
        .collect()
        .sink(receiveValue: {
          // Then
          XCTAssert(
            $0 == values,
            "Result was expected to be \(values) but was \($0)"
          )
        })
        .store(in: &subscriptions)
    }
XCTAssert(
  $0 == values + [1],
  "Result was expected to be \(values + [1]) but was \($0)"
)
  func test_flatMapWithMax2Publishers() {
    // Given
    typealias IntPublisher = PassthroughSubject<Int, Never>
    let intSubject1 = IntPublisher()
    let intSubject2 = IntPublisher()
    let intSubject3 = IntPublisher()
    let publisher = CurrentValueSubject<IntPublisher, Never>(intSubject1)
    let expected = [1, 2, 4]
    var results = [Int]()
    publisher
      .flatMap(maxPublishers: .max(2)) { $0 }
      .sink(receiveValue: {
        results.append($0)
      })
      .store(in: &subscriptions)
    // When
    intSubject1.send(1)
    publisher.send(intSubject2)
    intSubject2.send(2)
    publisher.send(intSubject3)
    intSubject3.send(3)
    intSubject2.send(4)
    publisher.send(completion: .finished)
    // Then
    XCTAssert(
      results == expected,
      "Results expected to be \(expected) but were \(results)"
    )
  }