Skip to Content
Course content

120: Snapshot Testing for UI

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a recurring trend when I review test suites from developers moving into senior roles: they believe that if their Unit Tests pass and they haven't touched the View code, the UI is "safe." The misconception is that logic coverage equals visual coverage. They think, "I've tested that the ViewModel provides the correct string to the label, so the label must be displaying correctly."

Here is why that's wrong. Imagine you have a UserProfileView. Your unit tests confirm that the user's name and bio are correctly passed into the view. Everything is green. But then, someone updates a global Theme file or modifies a UIStackView spacing constant in a base class. Suddenly, on an iPhone SE, the bio text is so long that it pushes the "Edit Profile" button completely off the bottom of the screen. Your unit tests still pass perfectly because the logic is intact, but your users are staring at a broken interface. Logic cannot "see" a layout collapse.

Logic Passes, But the Button is Invisible

This is the gap where snapshot testing lives. Instead of asserting that a property equals a value, snapshot testing takes a literal image of your view and compares it, pixel by pixel, to a "golden image" stored in your repository. If a single pixel shifts or a color changes from #F0F0F0 to #F1F1F1, the test fails.

I generally recommend using the swift-snapshot-testing library by Point-Free. It's far more flexible than the built-in XCTest options. It allows you to snapshot not just UIView or UIViewController, but even SwiftUI views and plain data structures.

Capturing the Source of Truth

When you write your first snapshot test, the library doesn't have an image to compare against. The first time you run the test, it will fail—but that's intentional. It records a reference image of the current state of the view and saves it to a folder in your project. This becomes your "Source of Truth."

import XCTest
import SnapshotTesting
@testable import YourApp

class UserProfileSnapshotTests: XCTestCase {
    func testUserProfileView_DefaultState() {
        let view = UserProfileView(name: "Jane Doe", bio: "Software Engineer and hiker.")
        view.frame = CGRect(x: 0, y: 0, width: 375, height: 667) // Simulate iPhone 8
        
        // This asserts that the current view matches the reference image on disk
        assertSnapshot(matching: view, as: .image)
    }
}

Now, if someone accidentally changes the font size of the bio to 40pt, the test will fail. The CI pipeline will stop, and you'll get a "diff" image highlighting exactly which pixels changed. It's an incredibly powerful way to catch regressions that would otherwise only be found by a manual QA pass or a frustrated user.

Handling the "Flakiness" of Pixels

A word of warning: snapshot tests can be brittle. If you run a test on an Intel Mac and your colleague runs it on an M1 Mac, or if one of you is using iOS 17.2 and the other is on 17.4, you might see tiny rendering differences in text anti-aliasing. This leads to "false positives" where the test fails but the UI looks identical to the human eye.

To solve this, I always suggest two things: first, standardize the environment (e.g., everyone uses the same simulator version in CI). Second, use a small precision threshold. Setting precision to 98% or 99% allows for those microscopic rendering differences while still catching the actual layout bugs that matter.

// Allow for 1% difference to avoid OS-version flake
assertSnapshot(matching: view, as: .image(precision: 0.99))



📋 Practical Task

Preventing Layout Regression in the OrderSummaryView

You are working on an e-commerce app. The OrderSummaryView displays the items purchased, the tax, and the total. A recent bug report indicates that when a product name is exceptionally long, it overlaps with the price label.

Your Task:

  • Create a snapshot test for OrderSummaryView.
  • Configure the view with a "Stress Test" data set: include a product name that is 100 characters long to ensure the layout handles wrapping correctly.
  • Write a second test case that snapshots the view in Dark Mode to ensure the text colors remain legible against the dark background.
  • Use a precision value of 0.98 to ensure the tests are stable across different developer machines.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.