> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 在 `bun test` 中使用快照测试

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

```ts snap.test.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { test, expect } from "bun:test";

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

***

首次执行此测试时，Bun 会评估传递给 `expect()` 的值，并将其写入与测试文件并列的名为 `__snapshots__` 的目录中。（注意输出中的 `snapshots: +1 added` 行。）

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun test test/snap
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
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 File Tree icon="folder-tree" theme={"theme":{"light":"github-light","dark":"dracula"}}
test
├── __snapshots__
│   └── snap.test.ts.snap
└── snap.test.ts
```

***

`snap.test.ts.snap` 文件是一个 JavaScript 文件，导出传入 `expect()` 值的序列化版本。这里 `{foo: "bar"}` 对象已被序列化为 JSON。

```js snap.test.ts.snap icon="file-code" theme={"theme":{"light":"github-light","dark":"dracula"}}
// Bun Snapshot v1, https://bun.com/docs/test/snapshots

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

***

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

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun test
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
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 terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun test --update-snapshots
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
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 测试运行器快照文档，请参见 [文档 > 测试运行器 > 快照](/test/snapshots)。
