iOS Snapshot Testing: Visual Regression Prevention with swift-snapshot-testing

iOS Snapshot Testing: Visual Regression Prevention with swift-snapshot-testing

Snapshot testing captures the rendered output of a view and compares it against a stored reference image. When the view changes unexpectedly, the test fails with a diff showing exactly what changed. This is the most practical way to prevent visual regressions in iOS apps without writing complex assertion code.

Why Snapshot Testing

Unit tests for UI logic (does the label show the right text?) miss layout bugs. XCUITest catches egregious failures but can't detect subtle visual regressions like incorrect spacing, wrong font weight, or color changes across light/dark modes.

Snapshot tests fill this gap: they record "this is what the view should look like" and fail when it looks different.

swift-snapshot-testing by Point-Free

The swift-snapshot-testing library from Point-Free is the standard tool for this. It supports multiple snapshot strategies beyond just PNG images.

Installation

Add to Package.swift:

.package(
    url: "https://github.com/pointfreeco/swift-snapshot-testing",
    from: "1.15.0"
)

Or in Package.swift test target:

.testTarget(
    name: "MyAppTests",
    dependencies: [
        "MyApp",
        .product(name: "SnapshotTesting", package: "swift-snapshot-testing")
    ]
)

Basic Usage

import XCTest
import SnapshotTesting
@testable import MyApp

class ProfileCardSnapshotTests: XCTestCase {
    func testProfileCardDefaultState() {
        let view = ProfileCardView(
            user: User(
                id: "1",
                name: "Alice Johnson",
                role: "iOS Engineer",
                avatarURL: nil
            )
        )
        view.frame = CGRect(x: 0, y: 0, width: 375, height: 120)
        
        assertSnapshot(of: view, as: .image)
    }
    
    func testProfileCardWithLongName() {
        let view = ProfileCardView(
            user: User(
                id: "2",
                name: "Alexander Constantine Maximilian III",
                role: "Senior Staff Principal Engineer",
                avatarURL: nil
            )
        )
        view.frame = CGRect(x: 0, y: 0, width: 375, height: 120)
        
        assertSnapshot(of: view, as: .image)
    }
}

On first run, assertSnapshot creates reference images in __Snapshots__/ProfileCardSnapshotTests/. Subsequent runs compare against these references.

Recording Mode

When you need to update snapshots after intentional design changes:

// Set isRecording = true to regenerate snapshots
assertSnapshot(of: view, as: .image, record: true)

// Or use the global flag in setUp
override func setUp() {
    // isRecording = true  // Uncomment to regenerate all snapshots
}

Never commit with isRecording = true—CI will always regenerate, never fail on regressions.

Snapshot Strategies

UIView

assertSnapshot(of: view, as: .image)
assertSnapshot(of: view, as: .image(precision: 0.99))  // 99% pixel match required
assertSnapshot(of: view, as: .image(size: CGSize(width: 375, height: 200)))

UIViewController

func testLoginViewControllerLayout() {
    let vc = LoginViewController()
    // Use iPhone SE size
    assertSnapshot(of: vc, as: .image(on: .iPhoneSe))
    // iPhone 14 Pro size
    assertSnapshot(of: vc, as: .image(on: .iPhone14Pro))
}

SwiftUI Views

import SwiftUI

func testSwiftUICardView() {
    let view = CardView(
        title: "Monthly Report",
        value: "$12,450",
        trend: .up
    )
    
    assertSnapshot(
        of: view,
        as: .image(layout: .fixed(width: 375, height: 200))
    )
}

Dark Mode and Accessibility

Test all appearance variants:

func testProfileCardAppearances() {
    let view = ProfileCardView(user: testUser)
    view.frame = CGRect(x: 0, y: 0, width: 375, height: 120)
    
    // Light mode
    assertSnapshot(of: view, as: .image, named: "light")
    
    // Dark mode
    view.overrideUserInterfaceStyle = .dark
    assertSnapshot(of: view, as: .image, named: "dark")
    
    // Large text
    view.overrideUserInterfaceStyle = .light
    // Simulate accessibility large text
    assertSnapshot(
        of: view,
        as: .image(traits: .init(preferredContentSizeCategory: .accessibilityExtraExtraLarge)),
        named: "large_text"
    )
}

Multiple Device Sizes

func testResponsiveLayoutAcrossDevices() {
    let vc = DashboardViewController()
    
    let devices: [(ViewImageConfig, String)] = [
        (.iPhoneSe, "iphone_se"),
        (.iPhone14Pro, "iphone_14_pro"),
        (.iPhone14ProMax, "iphone_14_pro_max"),
        (.iPadPro11, "ipad_pro_11")
    ]
    
    for (config, name) in devices {
        assertSnapshot(of: vc, as: .image(on: config), named: name)
    }
}

Non-Image Strategies

swift-snapshot-testing supports more than images:

View Hierarchy (.dump)

Snapshot the accessibility tree as text — fast, no image comparison:

func testButtonAccessibilityTree() {
    let button = ActionButton(title: "Submit Order", style: .primary)
    button.frame = CGRect(x: 0, y: 0, width: 200, height: 44)
    
    // Records as text — great for accessibility audits
    assertSnapshot(of: button, as: .accessibilityElements)
}

Recursive View Description

// Records the view hierarchy as descriptive text
assertSnapshot(of: view, as: .recursiveDescription)

Output looks like:

<UIView frame=(0, 0, 375, 120)
  | <UIImageView frame=(16, 16, 88, 88)>
  | <UILabel frame=(120, 24, 239, 22) text="Alice Johnson">
  | <UILabel frame=(120, 50, 239, 18) text="iOS Engineer">

This strategy is much faster than image comparison and catches structural changes.

Organizing Snapshot Files

By default, snapshots are stored next to the test file in __Snapshots__/. Commit them to version control:

MyApp/
  Tests/
    SnapshotTests/
      ProfileCardSnapshotTests.swift
      __Snapshots__/
        ProfileCardSnapshotTests/
          testProfileCardDefaultState.1.png
          testProfileCardWithLongName.1.png
          testProfileCardAppearances.dark.1.png
          testProfileCardAppearances.light.1.png

.gitattributes to prevent diff noise for PNG files:

Tests/**/__Snapshots__/**/*.png binary

CI Integration

Preventing Snapshot Generation in CI

override func setUp() {
    // Fail if snapshots don't exist in CI — never regenerate
    if ProcessInfo.processInfo.environment["CI"] != nil {
        diffTool = "ksdiff"  // Or any diff tool
    }
}

Better: use environment variable to control recording:

let isRecordingEnabled = ProcessInfo.processInfo.environment["RECORD_SNAPSHOTS"] == "true"

assertSnapshot(of: view, as: .image, record: isRecordingEnabled)

In CI, never set RECORD_SNAPSHOTS=true. Locally, run with it when updating baselines.

GitHub Actions

- name: Run Snapshot Tests
  run: |
    xcodebuild test \
      -scheme MyApp \
      -destination 'platform=iOS Simulator,name=iPhone 15,OS=17.0' \
      -testPlan SnapshotTests \
      2>&1 | xcpretty

- name: Upload Snapshot Diffs on Failure
  if: failure()
  uses: actions/upload-artifact@v4
  with:
    name: snapshot-diffs
    path: '**/FailureDiffs/'

When a snapshot test fails, swift-snapshot-testing writes the actual image and a diff to FailureDiffs/. Uploading these as artifacts lets you inspect regressions without local reproduction.

Handling Dynamic Content

Snapshots break on content that changes per run (dates, random IDs, live data). Fix it with controlled inputs:

func testOrderSummaryWithFixedDate() {
    // Use a fixed date — not Date()
    let order = Order(
        id: "ord-001",
        date: ISO8601DateFormatter().date(from: "2024-01-15T10:00:00Z")!,
        total: 99.99,
        items: [
            OrderItem(name: "Widget", quantity: 2, price: 49.99)
        ]
    )
    
    let view = OrderSummaryView(order: order)
    view.frame = CGRect(x: 0, y: 0, width: 375, height: 200)
    
    assertSnapshot(of: view, as: .image)
}

For network-loaded images, use a MockImageLoader that returns a fixed placeholder:

class MockImageLoader: ImageLoaderProtocol {
    func loadImage(from url: URL) -> AnyPublisher<UIImage, Error> {
        // Return consistent test image regardless of URL
        return Just(UIImage(named: "test_avatar", in: .module, with: nil)!)
            .setFailureType(to: Error.self)
            .eraseToAnyPublisher()
    }
}

Precision and Tolerance

Snapshots can fail due to anti-aliasing differences across simulator versions. Use precision tolerance:

// 98% pixel match — tolerates minor rendering differences
assertSnapshot(of: view, as: .image(precision: 0.98))

// Per-pixel color tolerance
assertSnapshot(of: view, as: .image(perceptualPrecision: 0.95))

perceptualPrecision uses a perceptual color difference algorithm (CIEDE2000) that's more lenient with anti-aliasing while still catching real regressions.

When NOT to Use Snapshot Testing

  • Views with highly dynamic content (live charts, real-time data)
  • Tests already covered by unit assertions (text content, enabled state)
  • Very simple views where a unit test is cheaper
  • Views where you only care about behavior, not appearance

Snapshot tests shine for: complex layouts, custom-drawn views, design system components, and views that need to look correct across multiple device sizes and color schemes.

Conclusion

swift-snapshot-testing turns visual review into an automated check. Record once when the design is correct. Every subsequent run detects regressions. The key disciplines are: commit snapshots to version control, never record in CI, test all relevant appearance variants (light/dark, device sizes, accessibility sizes), and use MockImageLoader to eliminate non-deterministic content.

Read more

Start now free