Skip to content

Bun のテストランナーは .toMatchSnapshot() を通じて Jest 風のスナップショットテストをサポートしています。

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

test("snapshot", () => {
  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 ファイルは、expect() に渡された値のシリアライズされたバージョンをエクスポートする JavaScript ファイルです。{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 by www.bunjs.com.cn 編集