Takes a snapshot of any view in your app, stores the reference and tests that the view looks the same.
- Swift Package Manager
class SnapshotViewTests: XCTestCase, SnapshotTestCase {
func test() async throws {
try await verifySnapshot {
SnapshotView()
}
}
}
NOTE: Works with both SwiftUI.View
and UIKit.UIViewController
.
-
You can specify the following in your Test scheme Launch Arguments:
-RecordingSnapshot
: If you want to have the test result be store directly in your reference folder -
You can specify the following in your Test scheme Launch Environment:
snapshotReferences
: The folder where the snapshot references are stored, default:.
snapshotFailures
: The folder where the failing test result will end up, default:../_Failures
snapshotTolerance
: A double which represents how much you allow the reference and result to diff, useful for CI environments, default: 0.0
- TIP: Add your
snapshotFailures
path to your.gitignore
file, it is not necessary to be stored in version control.
-
name
: If you want to specify a name, other than the autogenerated one based on your test class name and function name -
config
: What scenarios will the test verify, default: 6.1" device in light and dark mode
SnapshotConfig()
.add(device: .d6dot7) // testing light and dark mode for a 6.7" device
.add(device: Device(name: "iPad", width: 1024, height: 2048), interfaceStyle: .dark) // testing dark mode for a custom device
NOTE: This configuration will test 3 scenarios.
-
renderDelay
: Add a delay between rendering the view and taking the snapshot, if there is a need for the view to have time to load data, default: 0.4 -
viewBuilder/viewControllerBuilder
: The view/viewController to be tested
TIP: Instead of having to supply config
and renderDelay
for each test, you can override the default values. For instance, you can create a SnapshotTestCaseExtensions.swift
file and add the following code:
extension SnapshotConfig {
static var `default`: SnapshotConfig = SnapshotConfig()
.add(device: .d6dot1)
}
extension TimeInterval {
static var snapshotRenderDelay: TimeInterval = 0.4
}
If you have a test function called testHome()
in a test class HomeViewTests
in Tests/Home/HomeViewTests.swift
, the corresponding references should be located in $snapshotReferences/Home/HomeView_Home_{config}.png
.
If the test fails, or if there is no reference, the test will generate images in the failure path, including the reference so you can compare it to the failure, for instance $snapshotFailures/Home/HomeView_Home_{config}__REF.png
.
The file not containing __REF
you can move into your reference folder and it will now be compared against for future testing.
TIP: Make sure that you run the test agains the same test device. Even if you have configured different devices to test, the actually device you are running the test own will determine the quality of the generated snapshots and they could fail if you execute them on different devices.