运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

在 `bun test` 中使用快照测试

Bun 的测试运行器支持使用 .toMatchSnapshot() 进行 Jest 风格的快照测试。

snap.test.ts
import { test, expect } from "bun:test";

test("snapshot", () => {
  expect({ foo: "bar" }).toMatchSnapshot();
});

首次运行此测试时,Bun 会计算传入 expect() 的值,并将其写入测试文件旁的 __snapshots__ 目录。(注意输出中的 snapshots: +1 added 行。)

terminal
bun test test/snap
Text
test/snap.test.ts:
✓ snapshot [1.48ms]

 1 pass
 0 fail
 snapshots: +1 added
 1 expect() calls
Ran 1 test across 1 file. [82.00ms]

__snapshots__ 目录中包含了该目录下每个测试文件对应的 .snap 文件。

File
test
├── __snapshots__
│   └── snap.test.ts.snap
└── snap.test.ts

snap.test.ts.snap 文件是一个 JavaScript 文件,其中导出了传入 expect() 的值的序列化版本。Bun 会按照 Jest 的快照格式美化打印 {foo: "bar"} 对象,该格式并非严格的 JSON(请注意末尾的逗号)。

snap.test.ts.snap
// Bun Snapshot v1, https://bun.sh/docs/test/snapshots

exports[`snapshot 1`] = `
{
  "foo": "bar",
}
`;

在后续运行中,Bun 会读取快照文件,并将其与传入 expect() 的值进行比较。如果两者不同,测试就会失败。

terminal
bun test
Text
bun test v1.3.3 (9c68abdb)
test/snap.test.ts:
✓ snapshot [1.05ms]

 1 pass
 0 fail
 1 snapshots, 1 expect() calls
Ran 1 test across 1 file. [101.00ms]

要更新快照,请使用 --update-snapshots 标志。

terminal
bun test --update-snapshots
Text
bun test v1.3.3 (9c68abdb)
test/snap.test.ts:
✓ snapshot [0.86ms]

 1 pass
 0 fail
 snapshots: +1 added  # 快照已重新生成
 1 expect() calls
Ran 1 test across 1 file. [102.00ms]

请参阅快照。