Automatically generate snapshot tests for SwiftUI previews
SnapshotGen
Automatically generate snapshot tests for SwiftUI previews
Installation
Swift Package Manager
Add SnapshotGen and SnapshotTesting as dependencies in Package.swift
.
dependencies: [
.package(
url: "https://github.com/whiteio/SnapshotGen",
revision: "deeb172a353c40c2ccdb85803ffdb3ab5ac7eeeb"
),
]
Add SnapshotTesting as a dependency in your test target
targets: [
.target(name: "MyApp"),
.testTarget(
name: "MyAppTests",
dependencies: [
"MyApp",
.product(name: "SnapshotGenTesting", package: "SnapshotGen"),
]
)
]
Usage
Command Line
swift package generate-snapshots
Here’s the necessary command line arguments:
--input Directory or file containing SwiftUI previews to generate snapshots for
--output Directory to store the generate preview snapshots
--testable-import-name Name of the module containing the previews (used as @testable import ___MODULENAME___)
Example:
swift package generate-snapshots --input Sources/ --output Tests/ --testable-import-name ModuleName
Excluding SwiftUI Previews
SwiftUI previews can be excluded by adding an annotation above the struct which conforms to PreviewProvider
to prevent snapshot tests being generated for it. For example:
// snapshot-gen skip
struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView()
}
}
Annotations can be interleaved with documentation comments.
Troubleshooting
Due to the way images are created from SwiftUI previews the following error snapshot may be produced:
To resolve this, the preview can be set to a fixed size, e.g.
struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView()
.previewLayout(.fixed(width: 400, height: 900))
}
}