在 `bun test` 中使用快照測試
Bun 的測試執行器支援使用 .toMatchSnapshot() 進行 Jest 風格的快照測試。
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]
請參閱快照。