SwiftUI Previews

Providing Previews

Snapshot testing automatically finds all SwiftUI previews in your app and generates snapshots for each preview. This process tests your previews to ensure they all render without errors. Ensure your previews are included in uploads to Emerge to support snapshot testing, often this means uploading a debug build. Snapshots require the upload to be an XCArchive and the app to be built for arm64.

UIKit

Snapshots support both SwiftUI and UIKit, to make your snapshots visible to Emerge they need to be accessible from a PreviewProvider. To snapshot a UIKit view, return it from your PreviewProvider using UIViewRepresentable.

Preventing Flakiness

To reliably detect differences in images and prevent flaky diffs, each preview needs to render reproducibly. You can check if the environment variable EMERGE_IS_RUNNING_FOR_SNAPSHOTS is set to 1 to enable overrides such as mocking potentially volatile data. Commonly this applies to build versions, random numbers, or network responses. To help control for flakiness http requests through NSURL are blocked while generating snapshots, and the current time is mocked so NSDate will always return a constant time.

Components and Variants

Each PreviewProvider type is a single component, but can provide multiple variants. For example if your code looks like this:

struct MyComponent_Previews: PreviewProvider {
    static var previews: some View {
        MyView()
            .previewDisplayName("Light")
        MyView()
            .preferredColorScheme(.dark)
            .previewDisplayName("Dark")
    }
}

Then MyComponent will have two variants, named Light and Dark. When a component has multiple variants we recommend specifying the names so they can be easily distinguished when viewing the generated snapshots.

Automatic Variants

If your app supports dark mode or dynamic type, let us know if you want automatic generation of variants. For every variant in your binary, Emerge can create one in dark mode and one in light mode, or any combination of dynamic type settings.

Layout

Emerge respects the preview layout in previewLayout() when generating snapshots. The .device layout will result in a full screen preview. An iPhone SE 2022 is always used as the device type for previews. Use a .fixed layout or .sizeThatFits to customize the dimensions of your snapshot.

Code Coverage

Snapshot tests automatically generate code coverage reports as a ".profdata" file if your uploaded binary is built with code coverage information included. To test for code coverage information in the binary, look for the LLVM_COV segment in your binary.