Snapshot Testing: Catch Unintended UI Changes
Snapshot testing compares your UI to a saved 'golden' image, failing if pixels differ. It's a visual diff for your views, catching unintended regressions in layout or style. The main footgun is forgetting to re-record snapshots after intentional UI changes.
WHY IT EXISTS: Traditional unit tests are poor at verifying visual appearance. You can check a label's text, but not its font, color, truncation, and position relative to other elements without writing brittle, complex assertions. Snapshot testing solves this by checking the final rendered output.
THE MENTAL MODEL: Think of snapshot testing as a "spot the difference" game played by your CI server. The first time you run the test, you take a picture of your UI and call it "correct." On every subsequent run, you take a new picture and compare it to the original. If there's even a one-pixel difference, the test fails.
HOW IT WORKS: When you first run a snapshot test for a view, the library finds no existing reference. It saves the current rendered output as an image file (the "reference" or "golden" snapshot) and fails the test, instructing you to run it again. On the second run, it renders the view again and compares it pixel-by-pixel to the saved reference image. If they match, the test passes. If not, it fails and often generates a diff image showing the discrepancies. If a change is intentional, you can command the library to re-record the reference, approving the new version.
WHEN TO USE IT: Use snapshot testing for UI components with a complex or critical visual structure. It's perfect for design system components, custom views, table view cells, or entire view controllers. It provides a strong guarantee against visual regressions during code refactoring or when updating shared styles.
WHEN NOT TO USE IT: Avoid snapshotting views with dynamic, non-deterministic content like live dates, random numbers, or network-loaded data unless you can mock or stub that data consistently. It is not a replacement for unit tests that check logic; it is a complement that checks appearance. Be mindful that snapshots are image files that can increase your repository size.
ONE CANONICAL EXAMPLE: A common use case is testing a user profile card component. This card might have a user's name, avatar, and bio. A snapshot test ensures that changing a font style in the app's theme doesn't accidentally cause the bio text to overflow its container or overlap with the avatar. If a designer changes the layout intentionally, the developer simply re-records the snapshot to approve the new "golden" version.
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.