How do I inject mock services for previews in Combine with Swift?

When working with SwiftUI previews, particularly when dealing with Combine, it’s essential to inject mock services. This practice enables you to test UI components in isolation without relying on real dependencies. Below is an example of how to set up mock services for previews in Swift using Combine.

// Mock Service class MockUserService: UserServiceProtocol { func fetchUser() -> AnyPublisher { let mockUser = User(id: 1, name: "John Doe") return Just(mockUser) .setFailureType(to: Error.self) .eraseToAnyPublisher() } } struct UserView: View { @StateObject var viewModel: UserViewModel var body: some View { Text(viewModel.user?.name ?? "Loading...") .onAppear { viewModel.fetchUser() } } } struct UserView_Previews: PreviewProvider { static var previews: some View { let mockService = MockUserService() let viewModel = UserViewModel(userService: mockService) UserView(viewModel: viewModel) } }

SwiftUI Combine Mock Services Test UI User Service Dependency Injection Swift Previews