自动生成 SwiftUI 预览的快照测试

快照生成

自动生成 SwiftUI 预览的快照测试

Github操作

安装

Swift Package Manager

在 中添加 SnapshotGen 和 SnapshotTesting 作为依赖项。Package.swift

dependencies: [
  .package(
    url: "https://github.com/whiteio/SnapshotGen",
    revision: "deeb172a353c40c2ccdb85803ffdb3ab5ac7eeeb"
  ),
]

将快照测试添加为测试目标中的依赖项

targets: [
  .target(name: "MyApp"),
  .testTarget(
    name: "MyAppTests",
    dependencies: [
      "MyApp",
      .product(name: "SnapshotGenTesting", package: "SnapshotGen"),
    ]
  )
]

用法

命令行

swift package generate-snapshots

以下是必要的命令行参数:

--input Directory or file containing SwiftUI previews to generate snapshots for
--output Directory to store the generate preview snapshots
--testable-import-name Name of the module containing the previews (used as @testable import ___MODULENAME___)

Example:

swift package generate-snapshots --input Sources/ --output Tests/ --testable-import-name ModuleName

Excluding SwiftUI Previews

SwiftUI previews can be excluded by adding an annotation above the struct which conforms to to prevent snapshot tests being generated for it. For example:PreviewProvider

// snapshot-gen skip
struct ExampleView_Previews: PreviewProvider {
  static var previews: some View {
    ExampleView()
  }
}

Annotations can be interleaved with documentation comments.

Troubleshooting

Due to the way images are created from SwiftUI previews the following error snapshot may be produced:

Screen Shot 2023-03-15 at 21 31 13

To resolve this, the preview can be set to a fixed size, e.g.

struct ExampleView_Previews: PreviewProvider {
  static var previews: some View {
    ExampleView()
      .previewLayout(.fixed(width: 400, height: 900))
  }
}

GitHub

点击跳转