Snapshot 测试
Capture and compare serialized 输出使用 snapshots, and know 当不 到 use 它们.
你将学到
- 什么 snapshot 测试是 and 如何它 存储输出
- 编写 and 更新 snapshots 使用 toMatchInlineSnapshot
- 当 snapshots 添加值 and 当它们是 trap
- Reviewing snapshot diffs 到 avoid 假 confidence
概念讲解
What a Snapshot Does
A snapshot test serializes the output of your code — a rendered component, a serialized object, an error message — and stores it in a .snap file. On the next run, the test serializes the output again and compares it to the stored snapshot. If it differs, the test fails and shows a diff; you then decide whether the change is intentional (update the snapshot) or a bug (fix the code).
Writing Snapshots
In Vitest and Jest, expect(输出).toMatchSnapshot() writes or compares the snapshot. toMatchInlineSnapshot() stores the snapshot as a string literal inside the test file, which keeps the expected value visible and version-controlled alongside the test — preferable for small outputs. Run with the -u flag to update snapshots after an intentional change.
When They Help
Snapshots shine for stable, serializable output that is tedious to assert field-by-field: a deeply nested configuration object, a serialized AST, a large component render. They catch unintended changes to any field at once and produce a readable diff. They are also useful for regression tests on output you cannot easily enumerate.
When They Trap
Snapshots become a trap when developers blindly run -u to make the test pass without reading the diff. A snapshot that is updated without thought asserts nothing — it will always pass. Avoid snapshots for logic (use explicit assertions), for output with non-deterministic values (dates, random ids) unless you mask them, and for anything so large no one will review the diff. Treat every snapshot update as a code review item.
In Practice
Use toMatchInlineSnapshot for small outputs so the expected value lives in the test file and is visible during code review — reviewers can see exactly what changed. For larger outputs (a full component render), use an external .snap file but keep it under 50 lines; if it grows beyond that, the component is probably doing too much and should be split. Always mask non-deterministic values before snapshotting: replace dates with a placeholder, strip random ids, and normalize whitespace. When a snapshot fails in CI, never run -u remotely — pull the branch locally, read the diff, update intentionally, and commit with a message explaining why the output changed. A snapshot you can explain is a safety net; one you blindly accept is technical debt.
示例代码
import { describe, it, expect } from "vitest";
import { render } from "@testing-library/react";
import { UserCard } from "./UserCard";
describe("UserCard", () => {
it("matches the stored snapshot", () => {
const { container } = render(
<UserCard user={{ id: 1, name: "Ada", role: "admin" }} />
);
expect(container.firstChild).toMatchSnapshot();
});
it("serializes config deterministically", () => {
const config = buildConfig({ theme: "dark", lang: "en" });
expect(config).toMatchInlineSnapshot();
});
});
首先测试 snapshots rendered DOM; 其次 snapshots 配置对象 inline in 测试 file. Review diff on 每个更新.
动手试一试
常见错误
错误写法
运行 vitest -u 不使用读取 diff
正确做法
总是 review snapshot diff in code review. blindly 更新 snapshot asserts 无 and hides 真实 regressions.
错误写法
Snapshotting 输出使用 timestamps or random ids
正确做法
Mask 非-deterministic 值之前 snapshotting (replace dates 使用 fixed 字符串) 所以 snapshot 是 stable 跨越运行.
练习 Snapshot 测试
5 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。