一个用于在 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 预览。
导入 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()
}
}
https://github.com/doordash-oss/swiftui-preview-snapshots
Package.swift
中将该包添加为依赖项dependencies: [
.package(url: "https://github.com/doordash-oss/swiftui-preview-snapshots", from: "1.0.0"),
]
PreviewSnapshots
和 PreviewSnapshotsTesting
添加为你主要目标和测试目标的依赖项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。