Bun

指南测试运行器

bun test 中使用快照测试

Bun 的测试运行器支持 Jest 风格的快照测试,通过 .toMatchSnapshot()

snap.test.ts
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.3.0 (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://bun.net.cn/docs/test/snapshots

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

之后,当再次执行此测试文件时,Bun 将读取快照文件并将其与传递给 expect() 的值进行比较。如果值不同,测试将失败。

bun test
bun test v1.3.0 (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.3.0 (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 测试运行器快照的完整文档,请参阅 文档 > 测试运行器 > 快照