Skip to content

Instantly share code, notes, and snippets.

@pzmudzinski
Last active May 20, 2021 01:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pzmudzinski/52e51946a6108d5a607aac5d658880fc to your computer and use it in GitHub Desktop.
Save pzmudzinski/52e51946a6108d5a607aac5d658880fc to your computer and use it in GitHub Desktop.
CombineShoppingCartTests.swift
//
// CombineShoppingCartTests.swift
// CombineShoppingCartTests
//
// Created by Piotr on 25/03/2020.
// Copyright © 2020 Piotr. All rights reserved.
//
import XCTest
import Combine
@testable import CombineShoppingCart
fileprivate extension Product {
static let apple = Product(id: 1, name: "🍎", price: 5.0)
static let beer = Product(id: 2, name: "🍺", price: 10.0)
}
class CombineShoppingCartTests: XCTestCase {
private var cart: ShoppingCart!
override func setUp() {
self.cart = ShoppingCart()
}
func triggerCartActions(_ actions: CartAction...) {
Publishers.Sequence<[CartAction], Never>(sequence: actions)
.receive(subscriber: cart.input)
}
func testInsertingProduct() {
let expectation = XCTestExpectation(description: "Inserting new product")
let cancellable = cart.orders
.sink(receiveValue: { (orders) in
XCTAssertEqual([ProductOrder(product: .apple, quantity: 1)], orders)
expectation.fulfill()
})
triggerCartActions(.insert(product: .apple))
wait(for: [expectation], timeout: 5.0)
}
func testIncrementingProduct() {
let expectation = XCTestExpectation(description: "Incrementing existing product")
let cancellable = cart
.orders
.sink { (orders) in
if orders.contains(ProductOrder(product: .beer, quantity: 2)) {
expectation.fulfill()
}
}
triggerCartActions(
.insert(product: .apple),
.insert(product: .beer),
.incrementProduct(withId: Product.beer.id)
)
wait(for: [expectation], timeout: 5.0)
}
}
@skywalkerlw
Copy link

skywalkerlw commented May 20, 2021

This is amazing.

There's a problem in your solution.

if you separate action into two part rather than chaining, the second will not apply at all.

// origional

 triggerCartActions(
            .insert(product: .apple),
            .insert(product: .beer),
            .incrementProduct(withId: Product.beer.id)
        )

change to

 triggerCartActions(
            .insert(product: .apple)
        )

// insert  and incrementProduct does not happen at all
 triggerCartActions(
            .insert(product: .beer)
            .incrementProduct(withId: Product.beer.id)
        )

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