Testing ViewModels, Coordinators, UI & snapshots

testing · folio

In one line: Logic lives in a ViewModel and a router with injected dependencies, tested in-process in milliseconds; snapshots pin what a view looks like (one simulator, one reference file); UI tests drive the real app from another process through the accessibility tree — few, slow, addressed by identifier.

Download PDF Print view LaTeX source

Testing ViewModels, Coordinators, UI & snapshots — figure 1

ViewModel tests

  • A SwiftUI View is a value; what it renders is not readable through public API (third-party ViewInspector reflects on the View structs). So: thin View, logic in a VM. Test = construct with doubles → call an input → assert state.
  • State as an Equatable enum (idle · loading · loaded · error) and display strings computed in the VM (priceText == "$10.00"); #expect(a == b) prints both sides on failure. Inject what varies: API, clock, Date, UUIDs, locale.
  • Isolation: XCTest runs synchronous test methods on the main actor; Swift Testing runs every test on an arbitrary task → a @MainActor VM needs a @MainActor test or suite.
  • Sequences. ObservableObject: vm.$state.sink{seen.append($0)} gets the current value, then each new one — from willSet, so vm.state read inside the sink is still the old value. @Observable (Swift 5.9, iOS 17) has no publisher: withObservationTracking calls onChange once, on the first change — re-register per change. Observations{ vm.state } (Swift 6.2, iOS 26) is an AsyncSequence of transactions: mutations up to the next suspension point coalesce, so values can be skipped — not a recorder of every state.
  • To catch .loading, hold the double: a stub that suspends until the test releases it; assert mid-flight, then release.
  • Big state? assertSnapshot(of: vm.state, as: .dump) keeps a reviewed text reference instead of a page of hand-written expectations.
@MainActor @Suite struct FeedViewModelTests {
  @Test func offline_showsError() async {
    let vm = FeedViewModel(api: StubFeedAPI(.failure(URLError(.notConnectedToInternet))))
    await vm.load()
    #expect(vm.state == .error("Offline")) }
  @Test func loading_whileInFlight() async {
    let api = GatedFeedAPI()             // suspends until release()
    let vm = FeedViewModel(api: api)
    let load = Task { await vm.load() }
    await api.waitUntilCalled()
    #expect(vm.state == .loading)
    api.release(with: [.sample]); await load.value
    #expect(vm.state == .loaded([.sample])) } }

Coordinator / router tests

  • Test the decision (which route for which event), never a real push: inject a Router protocol and let a spy record calls.
  • SwiftUI: an @Observable router owns var path: [Route] bound to NavigationStack(path:) → assert the array. NavigationPath is type-erased — only count, isEmpty, append, removeLast, codable; elements can’t be read back (it is Equatable: compare with a path you build).
  • Deep links are pure functions URL → [Route]: table-test them with @Test(arguments:), one case per URL.
final class SpyRouter: Router {
  private(set) var shown: [Route] = []
  func show(_ r: Route) { shown.append(r) } }
@Test func selectingItem_routesToDetail() {
  let router = SpyRouter()
  FeedCoordinator(router: router).didSelect(Item(id: 7))
  #expect(router.shown == [.detail(id: 7)]) }   // the DECISION

Traps

  • Querying by label: app.buttons["Log in"] matches the label, passes in English, fails in a German run. accessibilityIdentifier is “for testing”, never shown or localized.
  • sleep(3): flaky when short, slow when long — wait for the element or property.
  • A gated stub never released hangs the run — give the suite .timeLimit(.minutes(1)) (minutes are the smallest unit).
  • UI tests on the real backend: nondeterministic, slow, may mutate data — stub by launch env.
  • CI on default .missing: a lost reference is re-recorded, the run fails, the retry passes → .never. Never commit .all. “Just re-record” approves a regression unseen.
  • Reference from another simulator or OS → fails on CI: pin model, OS, locale, appearance, text size; fix dates and IDs.
  • An interruption monitor for an expected alert never fires — tap the alert directly.

XCUITest toolkit (XCUIAutomation)

needAPI · fact
clean startlaunch(): synchronous; terminates a running instance; a launch failure halts the test
resumeactivate(): launches if needed, never terminates; reuses the last launch()’s args/env
configurelaunchArguments / launchEnvironment — changed after launch = next launch only; open(url) launches by URL
findapp.buttons["id"] matches identifier or title, label, value, placeholder; .element fails unless exactly 1 match, .firstMatch stops at the first (faster)
waitwaitForExistence(timeout:); Xcode 16: waitForNonExistence, wait(for: \.value, toEqual:, timeout:) → Bool · exists ≠ isHittable (a hit point can be computed)
alertsexpected → tap it; addUIInterruptionMonitor runs only when unrelated UI blocks an interaction; LIFO; true = cleared
stateresetAuthorizationStatus(for:) (iOS 13.4) · XCUIDevice.shared .orientation .appearance .location
a11ytry app.performAccessibilityAudit() (iOS 17): fails the test itself; handler true = ignore; on-screen only · Xcode 27: voiceOverService.moveForward() → speech
matrixrunsForEachTargetApplicationUIConfiguration = true: appearance × orientation × localization (Xcode 27 launch-test template)
perfXCTApplicationLaunchMetric · XCTHitchMetric (iOS 26)
evidenceXCTAttachment(screenshot:) default .deleteOnSuccess; test plan keeps video + screenshots of failing runs unless “On, and keep all”

Xcode 26 recording: the record button at the editor edge writes Swift, each line with alternative queries — prefer identifier over index. Report (Xcode 15+): video replay, Automation Explorer at the failure. Xcode 27: app-crash severity off / warning / failure / fatal per test plan. Swift Testing has no UI automation — UI tests stay XCTest.

override func setUpWithError() throws { continueAfterFailure = false }
@MainActor func test_login_showsWelcome() throws {
  let app = XCUIApplication()                 // the Target Application
  app.launchArguments += ["-AppleLanguages", "(de)"]
  app.launchEnvironment["STUB_SCENARIO"] = "loggedOut"
  app.launch()                                // args/env read HERE
  LoginPage(app: app).logIn(email: "a@b.co", password: "pw")
  XCTAssertTrue(app.staticTexts["welcome.title"].waitForExistence(timeout: 5))
  try app.performAccessibilityAudit() }
// Page Object: one type per screen owns its identifiers + actions

Snapshot tests (swift-snapshot-testing)

  • assertSnapshot(of:as:named:record:timeout:) (timeout 5 s). Strategies: .image (UIView, VC, SwiftUI), .recursiveDescription, .dump, .json, .plist, .raw (URLRequest); a text reference shows its diff readably in code review.
  • SwiftUI layout: .sizeThatFits (default) · .fixed(width:height:) · .device(config: .iPhone13); a config is size + safe area + traits only — newest iPhone preset iPhone13ProMax. traits: for dark mode / text size; drawHierarchyInKeyWindow: true to render UIAppearance and visual effects.
  • precision = share of pixels that must match; perceptualPrecision = how close each pixel must be (CILabDeltaE); 0.98–0.99 ≈ the human eye. Both default 1.
  • assertInlineSnapshot writes a text snapshot into the test source, as a trailing closure.

recordbehaviour (since 1.17, Jul 2024)
.missingdefault: record only absent references (and fail)
.allrewrite every reference — every assertion fails
.failedre-record only failing ones (keeps in-threshold passes untouched)
.nevera missing reference is a failure — for CI

Set per call (record:), per scope (withSnapshotTesting(record:)), per suite (@Suite(.snapshots(record:))) or per run (SNAPSHOT_TESTING_RECORD=never).

Which test sees what

testseesbreaks onmisses
VM unitstate, stringslogic changelayout, wiring
routerroutesflow changereal transitions
snapshotpixels / text dumpany pixel, new OSbehaviour, taps
UI (XCUITest)a11y tree of the real appcopy, timing, datainternals; slow

Report a problem ·Discuss this folio