快照与预览驱动的测试
捕获不同状态下的视觉回归问题。
快照与预览驱动的测试 是 CoddyKit 上的免费 SwiftUI Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 SwiftUI Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 SwiftUI Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Catching Visual Bugs
Some bugs are not crashes; they are layout slips you only see. Snapshot tests catch these by comparing images of your views. 👀
How Snapshots Work
A snapshot test renders a view to an image once, saves it, then fails later if a new render no longer matches.
The Reference Image
The first run records a trusted reference image. You review it by eye, and from then on it becomes the source of truth.
Previews Drive Testing
SwiftUI previews already show a view in many states. Designing those states first makes your snapshots easy to write.
#Preview { ProfileCard(user: .sample) }Cover Many States
Add previews for empty, loading, and error states. Each one becomes a snapshot, so regressions in any state are caught.
Test Light and Dark
Render each view in light and dark mode. A color that vanishes in dark mode is exactly what a snapshot will reveal. 🌗
.preferredColorScheme(.dark)Vary Dynamic Type
Snapshot a view at the largest Dynamic Type size too. Text that overflows or clips will fail the comparison immediately.
Pin the Device Size
Always snapshot on a fixed device or frame. Different screen sizes produce different images and cause false failures.
Reading a Failure
When a snapshot fails, the tool shows old, new, and a diff. You decide: a real bug, or an intended change to re-record.
Commit Your Snapshots
Store reference images in version control. Teammates then share the same baseline, and CI can catch visual changes in pull requests.
Re-Record on Purpose
Changed the design intentionally? Switch to record mode once to refresh the baselines, then turn it off again.
Quick Check
What does a snapshot test actually compare?
Recap
You learned snapshot testing: record a reference, cover many preview states, test light and dark, and commit baselines so visual bugs never sneak in. 🎉
常见问题解答
「快照与预览驱动的测试」课时是免费的吗?
是的 — 「快照与预览驱动的测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 SwiftUI Academy 课程的其余内容,请升级到 CoddyKit PRO。 SwiftUI Academy 课程共包含 4 节课。
「快照与预览驱动的测试」这节课中我会学到什么?
捕获不同状态下的视觉回归问题。 你通过在浏览器中直接运行的动手代码来练习 SwiftUI Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 SwiftUI Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 SwiftUI Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「快照与预览驱动的测试」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 SwiftUI Academy 课中编写并运行代码吗?
能。每节 SwiftUI Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。