0
0
iOS Swiftmobile~5 mins

Snapshot testing in iOS Swift

Choose your learning style9 modes available
Introduction

Snapshot testing helps you check if your app's screen looks right. It saves a picture of your UI and compares it later to find mistakes.

When you want to make sure your app's screen does not change by accident.
When you add new features and want to check the old screens still look good.
When you fix bugs and want to confirm the UI is still correct.
When you want to test different screen sizes or themes quickly.
When you want to catch visual errors before users see them.
Syntax
iOS Swift
import XCTest
import SnapshotTesting

class MyViewTests: XCTestCase {
  func testMyViewSnapshot() {
    let view = MyView()
    assertSnapshot(matching: view, as: .image)
  }
}

You need to import the SnapshotTesting library to use snapshot tests.

The assertSnapshot function compares the current UI to the saved snapshot image.

Examples
Check if the view looks the same as the saved image snapshot.
iOS Swift
assertSnapshot(matching: myView, as: .image)
Test the view snapshot on an iPhone screen size.
iOS Swift
assertSnapshot(matching: myView, as: .image(traits: UITraitCollection(userInterfaceIdiom: .phone)))
Save a new snapshot image instead of comparing. Use this when you want to update the snapshot.
iOS Swift
assertSnapshot(matching: myView, as: .image, record: true)
Sample App

This test creates a simple view with a label and checks if its appearance matches the saved snapshot image.

iOS Swift
import XCTest
import SnapshotTesting
import UIKit

class SimpleLabelView: UIView {
  let label = UILabel()
  override init(frame: CGRect) {
    super.init(frame: frame)
    label.text = "Hello Snapshot"
    label.textAlignment = .center
    label.frame = bounds
    addSubview(label)
  }
  required init?(coder: NSCoder) { nil }
}

class SimpleLabelViewTests: XCTestCase {
  func testSimpleLabelViewSnapshot() {
    let view = SimpleLabelView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
    assertSnapshot(matching: view, as: .image)
  }
}
OutputSuccess
Important Notes

Snapshot tests are great for catching visual bugs but should be used with care to avoid false failures.

Always review snapshot changes before updating snapshots to avoid hiding real bugs.

Use descriptive test names and organize snapshots well for easier maintenance.

Summary

Snapshot testing saves a picture of your UI to check for visual changes.

It helps catch accidental UI bugs early.

Use assertSnapshot with views and different device settings.