Skip to content

Commit

Permalink
Add a sample snapshot test for a SwiftUI View
Browse files Browse the repository at this point in the history
  • Loading branch information
pinarol committed Dec 13, 2024
1 parent 0f32fed commit 3d24405
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 0 deletions.
37 changes: 37 additions & 0 deletions Tests/GravatarUITests/AvatarPickerProfileViewTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
@testable import GravatarUI
import SnapshotTesting
import SwiftUI
import XCTest

final class AvatarPickerProfileViewTests: XCTestCase {
override func invokeTest() {
withSnapshotTesting(record: .failed) {
super.invokeTest()
}
}

@MainActor
func testAvatarPickerProfileView() throws {
let testView = AvatarPickerProfileView(
avatarURL: .constant(nil),
model: .constant(
.init(
displayName: "Shelly Kimbrough",
location: "San Antonio, TX",
profileURL: URL(string: "https://gravatar.com")
)
),
isLoading: .constant(false)
)
// put a border around so the bounds can be visible in the snapshots.
.markBounds()

assertSnapshots(
of: testView,
as: [
.testStrategy(userInterfaceStyle: .light),
.testStrategy(userInterfaceStyle: .dark),
]
)
}
}
18 changes: 18 additions & 0 deletions Tests/GravatarUITests/Snapshotting+Additions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import SnapshotTesting
import SwiftUI
import XCTest

extension Snapshotting where Value: SwiftUI.View, Format == UIImage {
static func testStrategy(userInterfaceStyle: UIUserInterfaceStyle = .light) -> Self {
let deviceConfig: ViewImageConfig = .iPhone13
let traits = UITraitCollection(traitsFrom: [
UITraitCollection(displayScale: deviceConfig.traits.displayScale),
UITraitCollection(userInterfaceStyle: userInterfaceStyle),
])

return .image(
layout: .device(config: deviceConfig),
traits: traits
)
}
}
13 changes: 13 additions & 0 deletions Tests/GravatarUITests/View+TestAdditions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import SwiftUI

extension View {
func markBounds() -> some View {
self
.padding(1) // to prevent borders from intersecting with content
.clipShape(RoundedRectangle(cornerSize: .zero))
.overlay(
RoundedRectangle(cornerSize: .zero)
.stroke(.red, lineWidth: 1)
)
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 3d24405

Please sign in to comment.