skip to content

In SwiftUI, how do you unit test an @Observable login view model against a fake auth service, and what should that test assert?

level: middleimportance: must knowfreq 72%

answer

  1. a protocol seam for the service
  2. a fake with a canned result
  3. no view, no rendering
  4. assert what the screen would show

basics

~20 s

Put the auth service behind a protocol passed to the @Observable model's init, and give the test a fake returning a canned success or error. Create the model directly, await signIn(), and assert on the state the view renders.

solid answer

~40 s

The model takes `any AuthService` through its `init`, so production passes the live client and a test passes a `FakeAuth` that returns a canned `Result`. The test never builds a view: it creates `LoginModel(auth:)`, sets `email` and `password`, awaits `signIn()` and asserts on what the screen would show, such as `errorMessage`, `user`, `isLoading` and `canSubmit`. Because the model is `@MainActor`, the test function is marked `@MainActor` too. In the app, the view gets the live service from a custom environment value declared with `@Entry`, and previews or snapshot tests swap in the fake with `.environment(\.authService, fake)`; the unit test skips the environment entirely, because SwiftUI resolves environment values only for views in a hierarchy.

code

swift · 22 lines
swift
import Testing

struct FakeAuth: AuthService {
    var result: Result<User, AuthError>
    func signIn(email: String, password: String) async throws -> User {
        try result.get()
    }
}

@MainActor
@Test func wrongPasswordShowsMessage() async {
    let model = LoginModel(auth: FakeAuth(result: .failure(.invalidCredentials)))
    model.email = "[email protected]"
    model.password = "correct-horse"
    #expect(model.canSubmit)

    await model.signIn()

    #expect(model.errorMessage == "Email or password is wrong.")
    #expect(model.user == nil)
    #expect(!model.isLoading)
}

go deeper

for a junior

Recall the three steps: build the model with a fake service, set the inputs, await the action and check the properties the screen shows.

for a middle

Explain why the service sits behind a protocol passed to init, why the test is @MainActor, and why the environment is the wrong path for a unit test.

for a senior

Argue for state assertions over call recording, and show which fake you need when a test must observe the loading state rather than only the end state.

for a principal

Set the convention that every screen model takes its services through init behind protocols, so tests and previews share fakes and no test touches the network.

## The seam: a protocol the model depends on A view model is testable when the thing it talks to can be replaced. For a login screen that is the **auth service**. Declare what the model needs as a protocol and let the model hold an existential: - `protocol AuthService: Sendable { func signIn(email:password:) async throws -> User }` - `init(auth: any AuthService)` on the model, storing it in a `private let`. Marking the protocol `Sendable` documents that a service value may be shared across tasks and actors, and a struct fake with only `Sendable` stored properties satisfies it for free. It is a design choice rather than a compiler demand: with the Xcode 27 toolchain this model also compiles in the Swift 6 language mode without it. ## The fake The simplest useful fake is a **stub**: a struct that returns whatever result the test configured. ```swift struct FakeAuth: AuthService { var result: Result<User, AuthError> func signIn(email: String, password: String) async throws -> User { try result.get() } } ``` It makes no network call, takes no time, and lets each test pick the branch it wants: `.success(User(name: "Ada"))` or `.failure(.invalidCredentials)`. The general taxonomy of stubs, fakes and mocks is covered in the lessons on test doubles; for a SwiftUI model a canned-result stub covers most tests. ## What the test does 1. **Arrange**: create `LoginModel(auth: FakeAuth(...))` directly. No view, no `UIHostingController`, no environment. 2. **Act**: set `email` and `password`, then `await model.signIn()`. Because `signIn()` is `async`, the test resumes only after the whole flow, including the `defer` that clears `isLoading`, has finished. 3. **Assert** on the model's public state. The test function is `@MainActor` because the model is. Without it, Swift 6 rejects the synchronous property reads and writes from a nonisolated test. ## What to assert Assert on **what the screen would show**, not on how the model got there: | Property | Why the screen cares | |---|---| | `canSubmit` | whether the Sign In button is enabled | | `isLoading` | whether the spinner shows (after the flow: `false`) | | `errorMessage` | the text under the form on failure | | `user` | whether the app moves on to the home screen | State assertions survive refactors: if you later add retry logic or caching inside `signIn()`, a test that checks `errorMessage == "Email or password is wrong."` still passes as long as the user sees the same thing. Recording calls on the fake ("was `signIn` called once with these arguments?") is worth it only when the call itself is the behaviour, such as making sure a disabled form never reaches the service. ## Where the environment fits In the app the screen needs to obtain the live service somewhere. A common SwiftUI approach is a custom environment value: ```swift extension EnvironmentValues { @Entry var authService: any AuthService = LiveAuth() } ``` The screen reads it with `@Environment(\.authService)` and passes it into the model's `init`. That gives two injection points with different jobs: - **The environment** swaps the service for a whole view subtree: a preview, a snapshot test of the rendered screen, or a UI-test build, with `.environment(\.authService, FakeAuth(...))`. - **The initializer** is what the unit test uses. Environment values are resolved for views inside a hierarchy, so a model created in a test never sees them; passing the fake to `init` is both simpler and explicit. Where a screen builds its view model, and when to prefer the environment over initializer parameters, are covered in the lessons on SwiftUI architecture and environment values. ## A checklist for one model test 1. One behaviour per test, named after what the user sees: `wrongPasswordShowsMessage`, not `testSignIn2`. 2. A fresh model and a fresh fake in every test, so no state leaks between tests that may run in parallel. 3. Inputs set through the same properties the view binds to (`email`, `password`), so the test exercises the real path. 4. Every observable outcome asserted: the message, the user, and that `isLoading` went back to `false`. ## Pitfalls - A model that creates its own `URLSession`-based client inside `init` has no seam; every test hits the network. - A test that asserts right after calling a non-`async` method that spawns a `Task` is checking work that has not started yet. - A fake that returns immediately can hide ordering bugs; the loading state needs a fake the test controls, which is a separate technique. - Asserting only that no error was thrown says nothing about what the user sees.

  • Why build a fresh model and fake inside each test instead of sharing them?
    Swift Testing runs tests in parallel by default, so shared mutable state lets one test's inputs leak into another. Building the model and fake inside each test keeps every test independent. If several tests share setup, put it in a suite type's `init`: each instance test function is called on a distinct instance of the suite.
  • Should the fake record the email and password it received?
    Only when the call is the behaviour under test, for example proving that `signIn()` trims whitespace from the email before sending it. For most tests, asserting on `errorMessage`, `user` and `isLoading` is stronger, because it keeps passing when the internals change and fails when the user would see something different.
  • How would a snapshot test of the login screen get the fake service?
    Through the environment: render the screen with `.environment(\.authService, FakeAuth(result: .failure(.invalidCredentials)))` so the subtree resolves the fake. The unit test does not need that path, because it constructs the model itself and passes the fake to `init`.

  • To test a view model you have to render the view
  • A model can read the fake service from @Environment in a unit test
  • The best assertion is that the fake's signIn was called
  • The test needs no main actor because the model is just a class
  • Using the live client with a test account is good enough for unit tests