Skip to content

Generated Xcode project 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 test uploads the images after the run, and Tuist compares them with the baseline.

Set up#

Add the package to Tuist/Package.swift:

swift
let package = Package(
name: "App",
dependencies: [
.package(url: "https://github.com/tuist/snapshots", .upToNextMinor(from: "0.1.0")),
]
)

Then add a unit test target that depends on your app and on TuistSnapshotsTesting, and a scheme that runs it. The scheme names the snapshot set:

swift
import ProjectDescription
let project = Project(
name: "App",
targets: [
// Your app target, named "App".
.target(
name: "AppSnapshotTests",
destinations: .iOS,
product: .unitTests,
bundleId: "dev.tuist.app-snapshot-tests",
deploymentTargets: .iOS("17.0"),
sources: ["Tests/AppSnapshotTests/**"],
dependencies: [
.target(name: "App"),
.external(name: "TuistSnapshotsTesting"),
]
),
],
schemes: [
.scheme(
name: "AppSnapshots",
buildAction: .buildAction(targets: [.target("App")]),
testAction: .targets([.testableTarget(target: "AppSnapshotTests")])
),
]
)

Add a test class to the target. Every preview becomes its own test:

swift
import TuistSnapshotsTesting
final class PreviewSnapshotTests: PreviewSnapshotTestCase {}

Run tuist install to fetch the package.

Run#

Run the scheme with tuist test, always on the same simulator, because a different device renders images of a different size:

bash
tuist test AppSnapshots --device "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.

Tip

With selective testing, a snapshot test target is only skipped once its images passed or were approved, so a rerun can't skip a target whose changes nobody reviewed. When a run skips targets, the images it didn't render count as skipped, not removed.

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.