Bun 的測試執行器透過 .toMatchSnapshot()
支援 Jest 風格的快照測試。
.toMatchInlineSnapshot()
方法尚未支援。
import { test, expect } from "bun:test";
test("snapshot", () => {
expect({ foo: "bar" }).toMatchSnapshot();
});
第一次執行此測試時,Bun 會評估傳遞給 expect()
的值,並將其寫入名為 __snapshots__
的目錄中,該目錄與測試檔案並列。(請注意輸出中的 snapshots: +1 added
行。)
bun test test/snap
bun test v1.x (9c68abdb)
test/snap.test.ts:
✓ snapshot [1.48ms]
1 pass
0 fail
snapshots: +1 added
1 expect() calls
Ran 1 tests across 1 files. [82.00ms]
__snapshots__
目錄包含目錄中每個測試檔案的 .snap
檔案。
test
├── __snapshots__
│ └── snap.test.ts.snap
└── snap.test.ts
snap.test.ts.snap
檔案是一個 JavaScript 檔案,用於匯出傳遞給 expect()
的值的序列化版本。{foo: "bar"}
物件已序列化為 JSON。
// Bun Snapshot v1, https://goo.gl/fbAQLP
exports[`snapshot 1`] = `
{
"foo": "bar",
}
`;
稍後,當再次執行此測試檔案時,Bun 會讀取快照檔案並將其與傳遞給 expect()
的值進行比較。如果值不同,測試將失敗。
bun test
bun test v1.x (9c68abdb)
test/snap.test.ts:
✓ snapshot [1.05ms]
1 pass
0 fail
1 snapshots, 1 expect() calls
Ran 1 tests across 1 files. [101.00ms]
若要更新快照,請使用 --update-snapshots
旗標。
bun test --update-snapshots
bun test v1.x (9c68abdb)
test/snap.test.ts:
✓ snapshot [0.86ms]
1 pass
0 fail
snapshots: +1 added # the snapshot was regenerated
1 expect() calls
Ran 1 tests across 1 files. [102.00ms]
請參閱 文件 > 測試執行器 > 快照,以取得使用 Bun 測試執行器進行模擬的完整文件。