> ## 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 测试运行器运行测试

Bun 有一个内置的[测试运行器](/test)，带有类 Jest 的 `expect` API。

***

要使用它，请从项目目录运行 `bun test`。测试运行器会递归搜索匹配以下模式的文件，并运行其中包含的测试。

```txt 文件树 icon="folder-tree" theme={null}
*.test.{js|jsx|ts|tsx}
*_test.{js|jsx|ts|tsx}
*.spec.{js|jsx|ts|tsx}
*_spec.{js|jsx|ts|tsx}
```

***

以下是典型运行的输出：三个测试文件（`test.test.js`、`test2.test.js` 和 `test3.test.js`），每个包含两个测试（`add` 和 `multiply`）。

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

```txt theme={null}
test.test.js:
✓ add [0.87ms]
✓ multiply [0.02ms]

test2.test.js:
✓ add [0.72ms]
✓ multiply [0.01ms]

test3.test.js:
✓ add [0.54ms]
✓ multiply [0.01ms]

 6 通过
 0 失败
 6 个 expect() 调用
跨 3 个文件运行了 6 个测试。 [9.00ms]
```

***

要只运行特定的测试文件，请向 `bun test` 传递一个位置参数。运行器只执行路径中包含该参数的文件。

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

```txt theme={null}
test3.test.js:
✓ add [1.40ms]
✓ multiply [0.03ms]

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

***

每个测试都有一个名称：即 `test` 函数的第一个参数。测试还可以使用 `describe` 分组为套件。

```ts theme={null}
import { test, expect, describe } from "bun:test";

describe("数学", () => {
  test("加法", () => {
    expect(2 + 2).toEqual(4);
  });

  test("乘法", () => {
    expect(2 * 2).toEqual(4);
  });
});
```

***

要按名称筛选测试，请使用 `-t`/`--test-name-pattern` 标志。

`-t add` 只运行名称中包含 "add" 的测试。该模式匹配用 `test` 定义的测试名称和用 `describe` 定义的套件名称。

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

```txt theme={null}
test.test.js:
✓ add [1.79ms]

test2.test.js:
✓ add [2.30ms]

test3.test.js:
✓ add [0.32ms]

 3 通过
 3 已过滤
 0 失败
 3 个 expect() 调用
跨 3 个文件运行了 3 个测试。 [59.00ms]
```

***

参见 [`bun test`](/test)。
