> ## 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` 通过将文件路径与一组模式匹配来确定要作为测试运行的文件。

## 默认发现逻辑

默认情况下，`bun test` 会递归搜索项目目录中匹配这些模式的文件：

* `*.test.{js|jsx|ts|tsx|mjs|cjs|mts|cts}` - 以 `.test.js`、`.test.jsx`、`.test.ts`、`.test.tsx`、`.test.mjs`、`.test.cjs`、`.test.mts` 或 `.test.cts` 结尾的文件
* `*_test.{js|jsx|ts|tsx|mjs|cjs|mts|cts}` - 以 `_test.js`、`_test.jsx`、`_test.ts`、`_test.tsx`、`_test.mjs`、`_test.cjs`、`_test.mts` 或 `_test.cts` 结尾的文件
* `*.spec.{js|jsx|ts|tsx|mjs|cjs|mts|cts}` - 以 `.spec.js`、`.spec.jsx`、`.spec.ts`、`.spec.tsx`、`.spec.mjs`、`.spec.cjs`、`.spec.mts` 或 `.spec.cts` 结尾的文件
* `*_spec.{js|jsx|ts|tsx|mjs|cjs|mts|cts}` - 以 `_spec.js`、`_spec.jsx`、`_spec.ts`、`_spec.tsx`、`_spec.mjs`、`_spec.cjs`、`_spec.mts` 或 `_spec.cts` 结尾的文件

## 排除项

默认情况下，`bun test` 忽略：

* `node_modules` 目录
* 隐藏目录（以点 `.` 开头的目录）
* 不具有 JavaScript 类扩展名的文件（基于可用的[加载器](/bundler/loaders)）

## 自定义测试发现

### 位置参数作为过滤器

要过滤运行的测试文件，请向 `bun test` 传递额外的位置参数：

```bash terminal icon="terminal" theme={null}
bun test <filter> <filter> ...
```

路径包含任一过滤器的测试文件将被运行。过滤器是子字符串匹配，而不是 glob 模式。

例如，要运行 `utils` 目录中的所有测试：

```bash terminal icon="terminal" theme={null}
bun test utils
```

这会匹配诸如 `src/utils/string.test.ts` 和 `lib/utils/array_test.js` 之类的文件。

### 指定精确的文件路径

要在测试运行器中运行特定文件，请确保路径以 `./` 或 `/` 开头，以便与过滤器名称区分：

```bash terminal icon="terminal" theme={null}
bun test ./test/specific-file.test.ts
```

### 按测试名称过滤

要按名称而非文件路径过滤测试，请使用带正则表达式模式的 `-t`/`--test-name-pattern` 标志：

```sh terminal icon="terminal" theme={null}
# 运行名称中包含 "addition" 的所有测试
bun test --test-name-pattern addition
```

该模式会与以空格分隔的、所有父级 `describe` 块标签为前缀的测试名称进行匹配。例如，定义为以下内容的测试：

```ts title="math.test.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
describe("Math", () => {
  describe("operations", () => {
    test("should add correctly", () => {
      // ...
    });
  });
});
```

此测试与字符串 "Math operations should add correctly" 匹配。

### 更改根目录

默认情况下，Bun 从当前工作目录开始查找测试文件。使用 `bunfig.toml` 中的 `root` 选项更改此行为：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
root = "src"  # 仅在 src 目录中扫描测试
```

## 执行顺序

测试按以下顺序运行：

1. 测试文件顺序运行（不并行）
2. 在每个文件中，测试按定义顺序运行
