DoorDash Jan 18, 2023

How to Speed Up SwiftUI Development and Testing Using PreviewSnapshots

Article Summary

John Flanagan from DoorDash reveals how his team eliminated duplicate code between SwiftUI previews and snapshot tests. The solution? An open-source tool that cuts testing boilerplate to a single line.

DoorDash's iOS Infrastructure team built PreviewSnapshots to solve a common pain point: developers were writing nearly identical code twice when using Xcode Previews for rapid UI iteration and SnapshotTesting for visual regression testing. The tool lets teams define view states once and reuse them across both workflows.

Key Takeaways

Critical Insight

PreviewSnapshots eliminates code duplication by letting developers write view configurations once for both Xcode Previews and snapshot testing, with automatic test generation for each preview state.

The article includes detailed code examples showing exactly how to refactor existing previews and tests, plus a complete example app on GitHub.

About This Article

Problem

SwiftUI developers at DoorDash were duplicating code when they tried to use Xcode Previews alongside SnapshotTesting. They had to write separate implementations for preview configurations and individual snapshot test functions for each view state.

Solution

John Flanagan's team built PreviewSnapshots, a generic tool that takes a collection of configurations and a configure closure. Developers define view states once using the NamedPreviewState protocol, and the tool generates both previews and tests from that single definition.

Impact

Complex views with multiple Bindings and arguments benefited most. Instead of writing multiple snapshot test functions, developers could call assertSnapshots() once and it would test all preview configurations against reference images on disk.

Recent from DoorDash

Related Articles