skip to content

Unit and Snapshot Checks

Testable SwiftUI keeps logic in models you can unit test and leaves views thin, with snapshot tests for rendering. Interviewers ask what you test in a screen and how you fake its services.

on this pageshow

explore

questions

6

In SwiftUI, why move a login screen's logic from body into an @Observable model, and what can a test check that a preview cannot?

level: juniorimportance: must knowfreq 70%

answer

  1. body describes, it does not decide
  2. SwiftUI owns the view's storage
  3. a plain class a test can create
  4. a preview is looked at, a test asserts

basics

~20 s

A SwiftUI body is a description SwiftUI evaluates on its own schedule, and SwiftUI manages @State storage for installed views. Logic in an @Observable model can be created, driven and asserted on in a unit test; a preview only shows a state.

solid answer

~40 s

A view's `body` returns a description of views that SwiftUI evaluates on its own schedule, and the storage behind `@State` is managed by SwiftUI for a view installed in a hierarchy. A test that just creates the view struct has nothing it can drive or read. So I move the rules (is the email plausible, is the password long enough, may the button be enabled) and the sign-in flow into an `@Observable` class: `canSubmit`, `isLoading`, `errorMessage`, `signIn()`. The view keeps only bindings and layout. A unit test then creates the model with a fake service, sets inputs, awaits `signIn()` and asserts on its properties, in milliseconds and on CI. A `#Preview` still earns its place, but it renders a state for a human eye: it asserts nothing and fails no build.

code

swift · 21 lines
swift
import SwiftUI

struct LoginView: View {
    @Bindable var model: LoginModel

    var body: some View {
        Form {
            TextField("Email", text: $model.email)
            SecureField("Password", text: $model.password)
            if let message = model.errorMessage {
                Text(message).foregroundStyle(.red)
            }
            Button("Sign In") {
                Task { await model.signIn() }
            }
            .disabled(!model.canSubmit)
            .accessibilityIdentifier("login.signIn")
            if model.isLoading { ProgressView() }
        }
    }
}

go deeper

for a junior

Recall that body only describes the screen and that SwiftUI owns @State storage. Name the properties you would move into the model and the one-line action the view keeps.

for a middle

Explain why a protocol-typed service passed through init is what makes the model testable, and draw the line between a rule in body and a display choice.

for a senior

Show the review rule you apply to pull requests: a business decision or service call in body is a defect, and the matching model test is part of the change.

for a principal

Frame thin views as what lets a team keep fast model tests as the bulk of its suite, with previews as a design aid rather than coverage.

## Why logic inside `body` resists testing In SwiftUI a view is a value type whose `body` property returns a **description** of the interface. SwiftUI decides when to evaluate `body` (for example, when a dependency it read changes) and what to draw from the result. Two consequences make logic that lives there hard to test: - **The output is not something you assert on.** `body` returns an opaque `some View`. SwiftUI's public API offers no way to ask that value "is the Sign In button disabled?" or "which message is showing?". Tools that walk a view tree from a test lean on SwiftUI internals. - **The state is not yours to read.** Apple's documentation for `@State` says SwiftUI manages the property's storage. That storage is live for a view installed in a hierarchy. A test that writes `let view = LoginView()` holds a struct whose state is not being managed by any running hierarchy. - **Side effects hide in closures.** A `Button` action that starts a `Task`, calls the network and writes three `@State` properties can only be exercised by tapping the button in a running app. Apple's sample-code article on managing model data states the alternative directly: separating the data model from the views "promotes modularity, improves testability". ## What moves into the model For a login screen the model holds everything that decides something: 1. **Inputs**: `email` and `password`, bound from the view with `$model.email`. 2. **Derived rules**: `canSubmit`, which combines an email check, a password length and `!isLoading`. 3. **The flow**: an `async` `signIn()` that sets `isLoading`, calls the auth service, then sets either `user` or `errorMessage`. 4. **The dependency**: the auth service, passed in through `init` behind a protocol so a test can hand in a fake. Marking the class `@Observable` lets SwiftUI track exactly which of those properties each view's `body` reads, and `@MainActor` keeps every mutation on the main actor where the view reads them. ## What stays in the view The view keeps what only SwiftUI can do: layout, bindings into the model, modifiers such as `.disabled(!model.canSubmit)`, and a one-line button action that calls `Task { await model.signIn() }`. A good review test: if a line in `body` contains an `if` that encodes a business rule, or a call to a service, it probably belongs in the model. An `if let message = model.errorMessage` that only chooses what to show is fine. What you then do **not** unit test: - that SwiftUI lays out a `Form` correctly; - that a `Button` calls its closure when tapped; - that `.disabled(true)` disables a control. Those are SwiftUI's own behaviour. Your test covers your rules. ## A preview versus a test | | `#Preview` | Unit test on the model | |---|---|---| | Who checks the result | a person looking at the canvas | an assertion | | What it proves | the screen looks right in this state | the rule produces this state | | Runs on CI | not as a check | yes | | Speed | renders a view | milliseconds, no rendering | | Catches a regression | only if someone looks | automatically | Previews and tests share one trick: both inject a fake service, so neither touches the network. The previews lesson covers mock data and `#Preview` traits; here the point is that a preview **shows** a state and a test **proves** it. ## How the test looks With the logic in the model, the test needs no SwiftUI at all: ```swift @MainActor @Test func shortPasswordCannotSubmit() { let model = LoginModel(auth: FakeAuth(result: .failure(.invalidCredentials))) model.email = "[email protected]" model.password = "short" #expect(!model.canSubmit) } ``` The same pattern covers the error message after a failed sign-in and the user after a successful one. Each test reads like a sentence about the screen's behaviour, and none of them depends on fonts, simulators or timing. ## Common mistakes - Keeping validation as a computed expression inside `body` because it is "just one line": it is still a rule nobody can test. - Treating a set of previews as the test suite for a screen. - Moving logic into the model but leaving the network call in the button closure, so the flow is still untestable. - Giving the model a concrete network client instead of a protocol, so the test has to hit a server.

  • Is a computed property on the view struct, such as var isValid: Bool, good enough for testing?
    Only partly. A test can create the struct and read a computed property that depends on stored `let` inputs, but the moment it reads `@State`, the value comes from storage SwiftUI manages for an installed view. Rules that depend on what the user typed belong in the model, where a test sets the inputs directly.
  • Does moving logic into an @Observable model cost anything at runtime?
    Very little, and it often helps. With Observation, SwiftUI tracks only the properties each `body` actually reads, so a change to `isLoading` updates views that read `isLoading` and leaves the rest alone. The cost is a reference type and a little indirection, which a login screen never notices.

  • Validation is one line in body, so it does not need a test
  • My previews show every state, so the screen is tested
  • A unit test can create the view and read its @State
  • Testing a SwiftUI screen means checking that the button is disabled in the UI
  • The network call can stay in the button closure once validation moves out
open as a page

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%

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.

open as a page

In SwiftUI, what does accessibilityIdentifier(_:) add to a login screen's Sign In button, and why do UI tests prefer it to the button's label?

level: juniorimportance: should knowfreq 50%

basics

~20 s

accessibilityIdentifier(_:) attaches a string to the view's accessibility element for tests; users never see or hear it. UI tests prefer it because the label is localized and reworded, while an identifier like login.signIn stays stable.

open as a page

In SwiftUI, what does a snapshot test of a login screen's error state check, and why do such tests break when the code has not changed?

level: middleimportance: should knowfreq 45%

basics

~20 s

A snapshot test renders a view in a fixed state and compares the image with a stored reference to catch visual change. It breaks without code changes when the OS, simulator, scale, color scheme, text size or locale differs from the recording.

open as a page

A SwiftUI login view model's test checks the loading spinner state after Task.sleep and fails intermittently on CI; how do you make that async test deterministic?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Make signIn() async so the test awaits the whole flow instead of sleeping. For the in-flight spinner, use a fake service that signals when called and suspends until the test releases it, and assert isLoading in between.

open as a page

As iOS lead on a SwiftUI app, how do you split testing of a feature like login across view model unit tests, snapshot tests and UI tests, and what do you leave untested?

level: principalimportance: should knowfreq 40%

basics

~20 s

Most coverage goes into fast unit tests on @Observable models with fake services; a few snapshot tests pin key visual states; a handful of UI tests guard the critical journey. SwiftUI's own layout and controls stay untested.

open as a page