PreviewSnapshots

一个用于在 SwiftUI 预览和 SnapshotTesting 快照测试之间共享视图配置的库。

用法

在预览中

导入 PreviewSnapshots 并在 PreviewProvider 实现上定义一个静态计算属性 snapshots

snapshots 中提供你需要的配置,然后从 previews 计算属性中返回 snapshots.previews

import PreviewSnapshots
import SwiftUI

struct ContentView: View {
    var message: String
    var isEnabled: Bool

    var body: some View { ... }
}

// MARK: - Previews

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        snapshots.previews.previewLayout(.sizeThatFits)
    }

    static var snapshots: PreviewSnapshots<String> {
        PreviewSnapshots(
            configurations: [
                .init(name: "Short Message", state: "Test"),

                .init(name: "Medium Message", state: "Medium length message"),

                .init(name: "Long Message", state: "This is a much longer message than the other messages being tested"),
            ],
            configure: { state in
                ContentView(message: state, isEnabled: true).padding()
            }
        )
    }
}

Xcode 将为每个提供的配置创建一个单独的 SwiftUI 预览。

screen shot of adding package to Xcode

在快照测试中

导入 PreviewSnapshotsTesting 并在测试中调用 ContentView_Previews.snapshots.assertSnapshots()

PreviewSnapshotsTesting 将为 snapshots 中定义的每个配置生成一个单独的快照,并将其与磁盘上的引用进行比较。

有关快照测试的更多信息,请参阅 SnapshotTesting 库。

import PreviewSnapshotsTesting
import XCTest

@testable import ContentModule

final class ContentViewSnapshotTests: XCTestCase {
    func test_snapshots() {
        ContentView_Previews.snapshots.assertSnapshots()
    }

    func test_disabled_snapshots() {
        // `PreviewProvider` can define multiple `PreviewSnapshot` collections to group like tests.
        ContentView_Previews.disabledSnapshots.assertSnapshots()
    }
}

安装

Xcode

  1. File 菜单中选择 Add Packages…
  2. 输入包存储库 URL: https://github.com/doordash-oss/swiftui-preview-snapshots
  3. 确认版本并让 Xcode 解析包
  4. 在最终对话框中,确保 PreviewSnapshotsAdd to Target 列设置为应用程序目标,并将 PreviewSnapshotsTestingAdd to Target 列更新为应用程序的测试目标

screen shot of adding package to Xcode

Swift Package Manager

  1. Package.swift 中将该包添加为依赖项
dependencies: [
    .package(url: "https://github.com/doordash-oss/swiftui-preview-snapshots", from: "1.0.0"),
]
  1. 分别将 PreviewSnapshotsPreviewSnapshotsTesting 添加为你主要目标和测试目标的依赖项
targets: [
    .target(
        name: "MyGreatApp"
        dependencies: [
            .product(name: "PreviewSnapshots", package: "swiftui-preview-snapshots"),
        ]
    ),
    .testTarget(
        name: "MyGreatAppTests",
        dependencies: [
            "MyGreatApp",
            .product(name: "PreviewSnapshotsTesting", package: "swiftui-preview-snapshots"),
        ]
    )
]

鸣谢

PreviewSnapshots 的灵感来自 Nataliya Patsovska Marmelstein 的 这个演讲

许可证

该库在 Apache 2.0 许可证下发布。 有关详细信息,请参阅 LICENSE