快照测试
学习如何在 Bun 中使用快照测试,在测试运行之间保存并比较输出
快照测试会保存某个值的输出,并将其与未来测试运行中的输出进行比较。它适用于 UI 组件、复杂对象,或任何需要保持一致的输出。
基本快照
使用 .toMatchSnapshot() 匹配器编写快照测试:
import { test, expect } from "bun:test";
test("snap", () => {
expect("foo").toMatchSnapshot();
});
第一次运行此测试时,Bun 会将传递给 expect 的参数序列化,并将其写入测试文件旁 __snapshots__ 目录中的快照文件。
快照文件
第一次运行后,Bun 会创建:
目录结构
your-project/
├── snap.test.ts
└── __snapshots__/
└── snap.test.ts.snap
快照文件内容如下:
__snapshots__/snap.test.ts.snap
// Bun 快照版本 1,https://bun.sh/docs/test/snapshots
exports[`snap 1`] = `"foo"`;
在之后的运行中,Bun 会将参数与磁盘上的快照进行比较。
更新快照
使用以下命令重新生成快照:
terminal
bun test --update-snapshots
当你有意更改输出时,请执行此操作。在 CI 环境中,除非传递此标志,否则 Bun 不会写入新的快照。
内联快照
对于较小的值,请使用 .toMatchInlineSnapshot()。Bun 会将内联快照直接存储在测试文件中:
import { test, expect } from "bun:test";
test("inline snapshot", () => {
// 首次运行:快照将自动插入
expect({ hello: "world" }).toMatchInlineSnapshot();
});
首次运行后,Bun 会自动更新你的测试文件:
import { test, expect } from "bun:test";
test("inline snapshot", () => {
expect({ hello: "world" }).toMatchInlineSnapshot(`
{
"hello": "world",
}
`);
});
使用内联快照步骤
- 使用
.toMatchInlineSnapshot()编写测试 - 运行一次测试
- Bun 会自动使用快照更新你的测试文件
- 后续运行时,Bun 会将该值与内联快照进行比较
错误快照
你还可以使用 .toThrowErrorMatchingSnapshot() 和 .toThrowErrorMatchingInlineSnapshot() 对错误消息进行快照:
import { test, expect } from "bun:test";
test("error snapshot", () => {
expect(() => {
throw new Error("Something went wrong");
}).toThrowErrorMatchingSnapshot();
expect(() => {
throw new Error("Another error");
}).toThrowErrorMatchingInlineSnapshot();
});
运行后,内联版本变为:
test("error snapshot", () => {
expect(() => {
throw new Error("Something went wrong");
}).toThrowErrorMatchingSnapshot();
expect(() => {
throw new Error("Another error");
}).toThrowErrorMatchingInlineSnapshot(`"Another error"`);
});
高级快照用法
复杂对象
快照适用于复杂的嵌套对象:
import { test, expect } from "bun:test";
test("complex object snapshot", () => {
const user = {
id: 1,
name: "John Doe",
email: "john@example.com",
profile: {
age: 30,
preferences: {
theme: "dark",
notifications: true,
},
},
tags: ["developer", "javascript", "bun"],
};
expect(user).toMatchSnapshot();
});
数组快照
数组同样适合快照测试:
import { test, expect } from "bun:test";
test("array snapshot", () => {
const numbers = [1, 2, 3, 4, 5].map(n => n * 2);
expect(numbers).toMatchSnapshot();
});
函数输出快照
快照函数的返回值:
import { test, expect } from "bun:test";
function generateReport(data: any[]) {
return {
total: data.length,
summary: data.map(item => ({ id: item.id, name: item.name })),
timestamp: "2024-01-01", // 测试时固定值
};
}
test("report generation", () => {
const data = [
{ id: 1, name: "Alice", age: 30 },
{ id: 2, name: "Bob", age: 25 },
];
expect(generateReport(data)).toMatchSnapshot();
});
React 组件快照
快照非常适合 React 组件:
import { test, expect } from "bun:test";
import { render } from "@testing-library/react";
function Button({ children, variant = "primary" }) {
return <button className={`btn btn-${variant}`}>{children}</button>;
}
test("Button component snapshots", () => {
const { container: primary } = render(<Button>Click me</Button>);
const { container: secondary } = render(<Button variant="secondary">Cancel</Button>);
expect(primary.innerHTML).toMatchSnapshot();
expect(secondary.innerHTML).toMatchSnapshot();
});
属性匹配器
对于在测试运行间会变化的值(比如时间戳或 ID),使用属性匹配器:
import { test, expect } from "bun:test";
test("snapshot with dynamic values", () => {
const user = {
id: Math.random(), // 每次运行都会变
name: "John",
createdAt: new Date().toISOString(), // 也会变化
};
expect(user).toMatchSnapshot({
id: expect.any(Number),
createdAt: expect.any(String),
});
});
快照文件存储:
快照文件
exports[`snapshot with dynamic values 1`] = `
{
"createdAt": Any<String>,
"id": Any<Number>,
"name": "John",
}
`;
最佳实践
保持快照文件简洁
// 推荐:聚焦的快照
test("user name formatting", () => {
const formatted = formatUserName("john", "doe");
expect(formatted).toMatchInlineSnapshot(`"John Doe"`);
});
// 避免:冗长难以审查的快照
test("entire page render", () => {
const page = renderEntirePage();
expect(page).toMatchSnapshot(); // 可能有数千行
});
使用描述性测试名称
// 推荐:清晰说明快照代表的内容
test("formats currency with USD symbol", () => {
expect(formatCurrency(99.99)).toMatchInlineSnapshot(`"$99.99"`);
});
// 避免:测试意图不明确
test("format test", () => {
expect(format(99.99)).toMatchInlineSnapshot(`"$99.99"`);
});
分组相关快照
import { describe, test, expect } from "bun:test";
describe("Button component", () => {
test("primary variant", () => {
expect(render(<Button variant="primary">Click</Button>))
.toMatchSnapshot();
});
test("secondary variant", () => {
expect(render(<Button variant="secondary">Cancel</Button>))
.toMatchSnapshot();
});
test("disabled state", () => {
expect(render(<Button disabled>Disabled</Button>))
.toMatchSnapshot();
});
});
处理动态数据
// 推荐:标准化动态数据
test("API response format", () => {
const response = {
data: { id: 1, name: "Test" },
timestamp: Date.now(),
requestId: generateId(),
};
expect({
...response,
timestamp: "TIMESTAMP",
requestId: "REQUEST_ID",
}).toMatchSnapshot();
});
// 或使用属性匹配器
test("API response with matchers", () => {
const response = getApiResponse();
expect(response).toMatchSnapshot({
timestamp: expect.any(Number),
requestId: expect.any(String),
});
});
管理快照
复查快照变更
当快照发生变化时,需仔细检查:
terminal
# 查看变更内容
git diff __snapshots__/
# 若变更是预期,则更新快照
bun test --update-snapshots
# 提交更新后的快照
git add __snapshots__/
git commit -m "Update snapshots after UI changes"
组织大型快照文件
对于大型项目,建议合理组织测试以保持快照文件可管理:
目录结构
tests/
├── components/
│ ├── Button.test.tsx
│ └── __snapshots__/
│ └── Button.test.tsx.snap
├── utils/
│ ├── formatters.test.ts
│ └── __snapshots__/
│ └── formatters.test.ts.snap
故障排除
快照失败
快照失败时,Bun 会显示差异:
diff
{
- "name": "John",
+ "name": "Jane",
}
- Expected - 1
+ Received + 1
常见原因:
- 有意更改(使用
--update-snapshots更新) - 无意更改(修正代码)
- 动态数据(使用属性匹配器)
- 环境差异(标准化数据)
平台差异
注意平台间的差异:
// Windows 与 Unix 路径可能不同
test("file operations", () => {
const result = processFile("./test.txt");
expect({
...result,
path: result.path.replace(/\\/g, "/"), // 统一路径格式
}).toMatchSnapshot();
});