> ## 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 的测试运行器如何发现和筛选项目中的测试文件

bun test 的文件发现机制决定了哪些文件会作为测试运行。理解其工作原理有助于你有效地组织测试文件。

## 默认发现逻辑

默认情况下，`bun test` 会递归搜索项目目录中符合特定模式的文件：

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

## 排除项

默认情况下，Bun 测试会忽略：

* `node_modules` 目录
* 隐藏目录（以句点 `.` 开头的目录）
* 没有 JavaScript 类扩展名的文件（基于可用的加载器）

## 自定义测试发现

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

你可以通过向 `bun test` 传递额外的位置参数来过滤运行的测试文件：

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun test <filter> <filter> ...
```

任何文件路径包含其中一个过滤器的测试文件都会被运行。这些过滤器是简单的子字符串匹配，而非通配符模式。

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

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

这将匹配类似 `src/utils/string.test.ts` 和 `lib/utils/array_test.js` 的文件。

### 指定精确文件路径

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

```bash terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun test ./test/specific-file.test.ts
```

### 按测试名称过滤

要根据测试名称而非文件路径过滤测试，使用 `-t`/`--test-name-pattern` 选项并传入正则表达式模式：

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

该模式会匹配一个由测试名称和其所有父 `describe` 块标签按空格连接组成的字符串。例如，定义如下测试：

```ts title="math.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"}}
describe("Math", () => {
  describe("operations", () => {
    test("should add correctly", () => {
      // ...
    });
  });
});
```

将匹配字符串 "Math operations should add correctly"。

### 更改根目录

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

```toml title="bunfig.toml" icon="settings" theme={"theme":{"light":"github-light","dark":"dracula"}}
[test]
root = "src"  # 仅扫描 src 目录下的测试
```

## 执行顺序

测试的执行顺序如下：

1. 测试文件按顺序执行（非并行）
2. 每个文件内的测试按照定义顺序顺序执行
