Xcode snapshots
- Snapshots enabled for your account. They are currently invite-only: reach out or ping us in the community Slack to request access.
- A project connected to Tuist.
- iOS 17 or macOS 14 to render previews.
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#
- In Xcode, add the
https://github.com/tuist/snapshotspackage, from version0.1.0. - Create a unit test target hosted by your app, for example
AppSnapshotTests, and link the package'sTuistSnapshotsTestingproduct to it. - Add a test class to that target. Every preview becomes its own test:
import TuistSnapshotsTesting
final class PreviewSnapshotTests: PreviewSnapshotTestCase {}
- 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:
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.
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.