Daily iOS
Testing

Testing a view model

If you were testing load() on the view model below, which cases would you verify?

@MainActor @Observable
final class FeedViewModel {
    enum State { case idle, loading, loaded([Post]), failed(String) }
    private(set) var state: State = .idle
    private let repo: PostRepository
    init(repo: PostRepository) { self.repo = repo }
    func load() async {
        state = .loading
        do { state = .loaded(try await repo.fetch()) }
        catch { state = .failed(error.localizedDescription) }
    }
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Inject a stub repository and verify success (data in loaded), failure (the failed message), an empty array (loaded([])), and the transition into loading right after the call. Errors and empty responses are where the real bugs gather, so success alone isn't enough.

Share a question