Skip to content

Xcode snapshots

Requirements

The tuist/snapshots library renders every SwiftUI preview in your app to an image, so you don't write snapshot tests by hand. tuist xcodebuild test uploads the images after the run, and Tuist compares them with the baseline.

Set up#

  1. In Xcode, add the https://github.com/tuist/snapshots package, from version 0.1.0.
  2. Create a unit test target hosted by your app, for example AppSnapshotTests, and link the package's TuistSnapshotsTesting product to it.
  3. Add a test class to that target. Every preview becomes its own test:
swift
import TuistSnapshotsTesting
final class PreviewSnapshotTests: PreviewSnapshotTestCase {}
  1. Add a scheme that runs the target, for example AppSnapshots. The scheme names the snapshot set.

Run#

Run the tests through tuist xcodebuild test, always on the same simulator, because a different device renders images of a different size:

bash
tuist xcodebuild test -scheme AppSnapshots -destination 'platform=iOS Simulator,name=iPhone 17'

In CI, the images the tests rendered are uploaded after the run, and the command fails when they changed and nobody approved the changes. Local runs upload nothing, because they would upload uncommitted changes.

Tune the comparison#

To tolerate small rendering differences, such as anti-aliasing, give a preview a diff threshold: the share of pixels, from 0 to 1, that may differ before the image counts as changed.

swift
import TuistSnapshots
#Preview {
ProfileView()
.snapshotDiffThreshold(0.02)
}

To leave previews out, override includes(_:) in your PreviewSnapshotTestCase subclass.

Options#

  • --no-snapshots (TUIST_TEST_SNAPSHOTS=false): turns uploads off in CI.
  • --snapshot-set <name> (TUIST_TEST_SNAPSHOT_SET): the set the images belong to. Defaults to the scheme.