iOS Snapshot Testing with Point-Free SnapshotTesting: Beyond Screenshots
Point-Free's swift-snapshot-testing is a flexible snapshot testing library that goes beyond UIView screenshots. It can snapshot any value — strings, data, models, network responses — using interchangeable strategies. This guide covers setup, common strategies, custom strategies, and how to manage snapshots in CI.
Key Takeaways
assertSnapshotis the core API — takes a value and a strategy, records or compares a snapshot.- Multiple strategies per value — snapshot a UIViewController as
.image,.recursiveDescription, or.accessibilityHierarchydepending on what you're testing. - Inline snapshots — string snapshots can live in the test file itself, no external file management needed.
recordmode creates new snapshots — setisRecording = trueto overwrite existing snapshots; remove the flag to test against them.- SwiftUI views require
UIHostingControllerwrapping — snapshot SwiftUI views the same way as UIKit views.
Most iOS developers have heard of snapshot testing as "screenshot testing" — capture what the screen looks like, compare against a reference. That's valid but undersells what snapshot testing can do.
Point-Free's swift-snapshot-testing library separates the concept of "what to snapshot" (the value) from "how to represent it" (the strategy). The strategy can be a PNG, a text description, JSON, or anything else you define. This makes snapshot testing applicable far beyond visual regression.
Installation
Add to your Package.swift or via Xcode's SPM integration:
// Package.swift
dependencies: [
.package(
url: "https://github.com/pointfreeco/swift-snapshot-testing",
from: "1.16.0"
)
],
targets: [
.testTarget(
name: "MyAppTests",
dependencies: [
.product(name: "SnapshotTesting", package: "swift-snapshot-testing")
]
)
]Basic Usage
import XCTest
import SnapshotTesting
final class LoginViewTests: XCTestCase {
func testLoginView() {
let vc = LoginViewController()
vc.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
assertSnapshot(of: vc, as: .image)
}
}On first run, the test creates a __Snapshots__ directory alongside the test file and saves a reference image. On subsequent runs, it compares against the reference.
Built-In Strategies
Image Strategies
// UIViewController as PNG screenshot
assertSnapshot(of: viewController, as: .image)
// With specific device size
assertSnapshot(of: viewController, as: .image(on: .iPhone13Pro))
// UIView as image
assertSnapshot(of: myView, as: .image)
// Specific size
assertSnapshot(of: myView, as: .image(size: CGSize(width: 375, height: 200)))Device presets include .iPhone13Pro, .iPadPro11, .iPhoneSE, and others. Use these instead of hardcoded sizes for consistent tests across machines.
Text Strategies
// View hierarchy description (like `po view.debugDescription` in lldb)
assertSnapshot(of: viewController, as: .recursiveDescription)
// Output:
// <UIView: 0x...> frame=(0, 0; 390, 844)
// | <UILabel: 0x...> text='Log in' frame=(20, 100; 350, 44)
// | <UITextField: 0x...> frame=(20, 160; 350, 44)Hierarchy snapshots are less brittle than image snapshots for testing structure without caring about exact pixels.
Accessibility Hierarchy
// Accessibility element tree — great for accessibility testing
assertSnapshot(of: viewController, as: .accessibilityHierarchy)This snapshots the accessibility element tree as text. It catches changes to accessibility labels, traits, and element ordering without requiring visual comparison.
Network Requests
// Snapshot URLRequest for API testing
let request = URLRequest(url: URL(string: "https://api.example.com/users")!)
assertSnapshot(of: request, as: .raw)
// Outputs:
// GET https://api.example.com/users
// Accept: */*Data and Encodable Types
// JSON encoding of a model
struct User: Codable {
let id: Int
let name: String
let email: String
}
let user = User(id: 1, name: "Alice", email: "alice@example.com")
assertSnapshot(of: user, as: .json)
// Snapshot:
// {
// "email" : "alice@example.com",
// "id" : 1,
// "name" : "Alice"
// }JSON snapshots are extremely useful for testing API response parsing — if the JSON representation of your model changes, the test fails.
SwiftUI Testing
SwiftUI views require wrapping in UIHostingController:
import SwiftUI
import SnapshotTesting
final class ContentViewTests: XCTestCase {
func testContentView() {
let view = ContentView(model: ContentViewModel(title: "Hello", subtitle: "World"))
let vc = UIHostingController(rootView: view)
vc.view.frame = UIScreen.main.bounds
assertSnapshot(of: vc, as: .image(on: .iPhone13))
}
func testContentViewDarkMode() {
let view = ContentView(model: ContentViewModel(title: "Hello", subtitle: "World"))
let vc = UIHostingController(rootView: view)
vc.overrideUserInterfaceStyle = .dark
vc.view.frame = UIScreen.main.bounds
assertSnapshot(of: vc, as: .image(on: .iPhone13), named: "dark-mode")
}
}Test multiple configurations by providing a named parameter to distinguish snapshots:
func testLoginViewInAllSizes() {
let vc = LoginViewController()
let devices: [(String, ViewImageConfig)] = [
("iphone-se", .iPhoneSe),
("iphone-15", .iPhone13),
("iphone-15-pro-max", .iPhone13ProMax),
("ipad-pro", .iPadPro12_9),
]
for (name, config) in devices {
assertSnapshot(of: vc, as: .image(on: config), named: name)
}
}Inline Snapshots
String-based strategies support inline snapshots — the reference is stored in the test file itself, not in a separate directory:
func testUserDescription() {
let user = User(id: 1, name: "Alice", email: "alice@example.com")
assertInlineSnapshot(of: user, as: .json) {
"""
{
"email" : "alice@example.com",
"id" : 1,
"name" : "Alice"
}
"""
}
}On first run, the closure body is filled in automatically by the test runner. On subsequent runs, it compares against the inline string.
Inline snapshots are ideal for:
- Short text outputs
- Model serialization
- Simple view descriptions
They're not suitable for image snapshots (images are binary and can't be stored inline).
Custom Strategies
Define strategies for your own types:
// Strategy for testing view background color
extension Snapshotting where Value == UIView, Format == String {
static var backgroundColor: Snapshotting {
return Snapshotting<UIView, String>.init(
pathExtension: "txt",
diffing: .lines
) { view in
let color = view.backgroundColor ?? .clear
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: &a)
return String(format: "rgba(%.2f, %.2f, %.2f, %.2f)", r, g, b, b, a)
}
}
}
// Usage
assertSnapshot(of: myView, as: .backgroundColor)A more practical custom strategy — snapshot a view model's state:
extension Snapshotting where Value == CheckoutViewModel, Format == String {
static var state: Snapshotting {
return Snapshotting<CheckoutViewModel, String>.init(
pathExtension: "txt",
diffing: .lines
) { vm in
"""
items: \(vm.items.count)
subtotal: \(vm.subtotal)
tax: \(vm.tax)
total: \(vm.total)
canCheckout: \(vm.canCheckout)
"""
}
}
}Recording Mode
When you add new snapshot tests or deliberately change UI, you need to update reference snapshots:
// Record all snapshots in this file
class LoginViewTests: XCTestCase {
override func setUp() {
isRecording = true // Remove this after recording
}
}
// Or per-assertion
assertSnapshot(of: view, as: .image, record: true)Important in CI: never set isRecording = true without a mechanism to capture the resulting images. In CI, recording mode is typically an error — if you're recording, you should commit the snapshots before merging.
Some teams add a check:
override func setUp() {
// Fail if recording mode is on in CI
if ProcessInfo.processInfo.environment["CI"] != nil {
XCTAssertFalse(isRecording, "isRecording must be false in CI")
}
}Managing Snapshots in CI
Snapshot files must be committed to version control. When snapshots change, the diff is visible in code review — reviewers can see visual changes without running the app.
Git LFS for large image files:
git lfs track "**/__Snapshots__/**/*.png"This is optional but keeps your repository size manageable for projects with many snapshot tests.
Snapshot failures in CI = failing tests:
When a UI change breaks snapshots, the CI test failure includes the diff as a test attachment in the .xcresult. Upload the result bundle as an artifact:
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: test-results
path: TestResults.xcresultReviewers can download the artifact and open it in Xcode to see the visual diff.
When to Use Each Strategy
| Scenario | Strategy |
|---|---|
| Visual regression on a view | .image |
| Structure of view hierarchy | .recursiveDescription |
| Accessibility labels and traits | .accessibilityHierarchy |
| API model serialization | .json |
| Simple text output | Inline snapshot |
| API request format | .raw |
| Dark/light mode variants | .image with named: |
| Multiple device sizes | .image(on: device) with named: |
The multi-strategy approach is what makes swift-snapshot-testing more powerful than screenshot-only alternatives. Use the right strategy for what you're actually testing.