Reducing flakes

Previews need to be deterministic in order to render consistently between snapshot runs.

Here are a few tips for common issues we see:

  1. Don't perform any live network calls. Instead, use a fake network client that serves requests from disk.
  2. Avoid displaying random values like UUID.
  3. Display fixed dates rather than the current time.
  4. Use a fixed build version.

iOS

To help control for flakiness, HTTP requests through NSURL are blocked while generating snapshots.

If you'd like to conditionally set code when a preview is being rendered by our system, you can check whether the EMERGE_IS_RUNNING_FOR_SNAPSHOTS environment variable is set to "1". For example:

if ProcessInfo.processInfo.environment["EMERGE_IS_RUNNING_FOR_SNAPSHOTS"] == "1" {
  return "10 minutes ago"
}

Custom Precision

You can reduce the amount of precision required for images to be considered unchanged using EmergePrecisionModifier. Add it to your preview by linking SnapshotPreviewsCore from the SDK and calling .emergeSnapshotPrecision(...) For example the following preview will only be marked as changed if the diff is greater than 1%.

struct MyComponent_Previews: PreviewProvider {
    static var previews: some View {
        MyView()
            .previewDisplayName("Light")
            .emergeSnapshotPrecision(0.99)
    }
}

The percentage difference is calculated based on the perceptual difference between pixels, with colors that are more different having a higher percent difference.