How do I unit test view models in Combine with Swift?

Unit testing view models in Swift using Combine allows for the verification of your business logic, ensuring that your application is both robust and maintainable. By leveraging Combine’s features, you can create reactive UI components while keeping your testing straightforward and effective.
unit testing, view models, Combine, Swift, reactive programming, testing strategies

    import Combine
    import XCTest

    // Example ViewModel
    class MyViewModel {
        @Published var text: String = ""
        var cancellables = Set()

        func updateText(with value: String) {
            text = value
        }
    }

    // Unit Tests
    class MyViewModelTests: XCTestCase {
        var viewModel: MyViewModel!
        var cancellables: Set!

        override func setUp() {
            super.setUp()
            viewModel = MyViewModel()
            cancellables = []
        }

        override func tearDown() {
            viewModel = nil
            cancellables = nil
            super.tearDown()
        }

        func testTextUpdate() {
            let expectation = XCTestExpectation(description: "Text should update")

            viewModel.$text
                .dropFirst() // Ignore the initial value
                .sink(receiveValue: { newValue in
                    XCTAssertEqual(newValue, "Hello, World!")
                    expectation.fulfill()
                })
                .store(in: &cancellables)

            viewModel.updateText(with: "Hello, World!")

            wait(for: [expectation], timeout: 1.0)
        }
    }
    

unit testing view models Combine Swift reactive programming testing strategies