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?
answer
- body describes, it does not decide
- SwiftUI owns the view's storage
- a plain class a test can create
- a preview is looked at, a test asserts
basics
~20 sA 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 sA 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 linesimport 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
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.
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.
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.
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