22.6 · Testing SwiftUI, tvOS focus, and watchOS logic
SwiftUI views are hard to unit-test directly, and the less common platforms have fewer test tools. The way through is the same everywhere: test the logic as plain Swift, and spend UI tests only where they are the only option.
Mental model. Keep decisions out of views, behind a model you can test without a screen, and test the thin view layer with snapshots or a few UI tests.
SwiftUI
View models, hosting, ImageRenderer and ViewInspector.
- How do you test SwiftUI: view models, hosting a view, ImageRenderer snapshots and ViewInspector?
A SwiftUI View is a value that describes UI; there is no object to poke, so the first and best strategy is to test the logic, not the view. Move decisions…
tvOS and watchOS
Focus tests, remote input and testing connectivity and widgets without a device.
- How do you test tvOS focus and remote input, and watchOS connectivity and complications, when UI testing on those platforms is limited?
tvOS UI tests use the same XCUIApplication but with the remote as the input: XCUIRemote.shared.press(.right) (and .up, .down, .select, .menu, .playPause) and…
More in Testing
- 22.1 · The pyramid, and what not to test
- 22.2 · XCTest and Swift Testing
- 22.3 · Async tests, expectations and controlling time
- 22.4 · Fakes, mocks and the inputs that make tests random
- 22.5 · Snapshot tests and UI tests
- 22.7 · Flakes, hermetic CI, and a quality system for a large team
- 22.8 · Swift Testing in depth: arguments, traits, errors, confirmations, isolation and scoping
- 22.9 · XCTest lifecycle and expectations, Sendable doubles, and the main actor in tests