Skip to content

Bun 的測試運行器通過 .toMatchSnapshot() 支持 Jest 風格的快照測試。

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

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

第一次執行此測試時,Bun 將評估傳遞給 expect() 的值並將其寫入與測試文件一起存放的名為 __snapshots__ 的目錄中的磁盤上。(注意輸出中的 snapshots: +1 added 行。)

sh
bun test test/snap
txt
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 文件。

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

snap.test.ts.snap 文件是一個 JavaScript 文件,它導出了傳遞給 expect() 的值的序列化版本。{foo: "bar"} 對象已被序列化為 JSON。

js
// Bun Snapshot v1, https://bun.com/docs/test/snapshots

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

稍後,當再次執行此測試文件時,Bun 將讀取快照文件並將其與傳遞給 expect() 的值進行比較。如果值不同,測試將失敗。

sh
bun test
txt
bun test v1.3.3 (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 標志。

sh
bun test --update-snapshots
txt
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 tests across 1 files. [102.00ms]

請參閱 文檔 > 測試運行器 > 快照 獲取使用 Bun 測試運行器進行快照的完整文檔。

Bun學習網由www.bunjs.com.cn整理維護