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

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

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

```ts snap.test.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { test, expect } from "bun:test";

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

***

首次运行此测试时，Bun 会计算传递给 `expect()` 的值，并将其写入测试文件旁边的 `__snapshots__` 目录中。（注意输出中的 `snapshots: +1 added` 行。）

```sh terminal icon="terminal" theme={null}
bun test test/snap
```

```txt theme={null}
test/snap.test.ts:
✓ 快照 [1.48ms]

 1 通过
 0 失败
 快照：+1 已添加
 1 个 expect() 调用
跨 1 个文件运行了 1 个测试。 [82.00ms]
```

***

`__snapshots__` 目录中包含了每个测试文件的 `.snap` 文件。

```txt 文件树 icon="folder-tree" theme={null}
test
├── __snapshots__
│   └── snap.test.ts.snap
└── snap.test.ts
```

***

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

```js snap.test.ts.snap icon="file-code" theme={null}
// Bun Snapshot v1, https://bun.sh/docs/test/snapshots

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

***

在后续运行时，Bun 会读取快照文件并将其与传递给 `expect()` 的值进行比较。如果不同，测试失败。

```sh terminal icon="terminal" theme={null}
bun test
```

```txt theme={null}
bun test v1.3.3 (9c68abdb)
test/snap.test.ts:
✓ 快照 [1.05ms]

 1 通过
 0 失败
 1 个快照，1 个 expect() 调用
跨 1 个文件运行了 1 个测试。 [101.00ms]
```

***

要更新快照，请使用 `--update-snapshots` 标志。

```sh terminal icon="terminal" theme={null}
bun test --update-snapshots
```

```txt theme={null}
bun test v1.3.3 (9c68abdb)
test/snap.test.ts:
✓ 快照 [0.86ms]

 1 通过
 0 失败
 快照：+1 已添加  # 快照已重新生成
 1 个 expect() 调用
跨 1 个文件运行了 1 个测试。 [102.00ms]
```

***

参见 [快照](/test/snapshots)。
