> ## 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.

# 测试配置

> 使用 bunfig.toml 和命令行选项配置 bun test 的行为

使用 `bunfig.toml` 和命令行选项配置 `bun test`。

## 配置文件

要在 `bunfig.toml` 中配置 `bun test`，请添加 `[test]` 部分：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
# 选项写在这里
```

## 测试发现

### root

`root` 选项设置 Bun 扫描测试的目录，而不是项目根目录。

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

#### 示例

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

# 在特定的测试目录中运行测试
root = "tests"

# 在多个指定目录中运行测试（当前不支持——请改用模式）
# root = ["src", "lib"]  # 此语法不支持
```

### 预加载脚本

`preload` 选项在测试运行前加载脚本：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
preload = ["./test-setup.ts", "./global-mocks.ts"]
```

这等同于在命令行中使用 `--preload`：

```bash terminal icon="terminal" theme={null}
bun test --preload ./test-setup.ts --preload ./global-mocks.ts
```

#### 常见预加载用例

```ts title="test-setup.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
// 全局测试设置
import { beforeAll, afterAll } from "bun:test";

beforeAll(() => {
  // 设置测试数据库
  setupTestDatabase();
});

afterAll(() => {
  // 清理
  cleanupTestDatabase();
});
```

```ts title="global-mocks.ts" icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
// 全局模拟
import { mock } from "bun:test";

// 模拟环境变量
process.env.NODE_ENV = "test";
process.env.API_URL = "http://localhost:3001";

// 模拟外部依赖
mock.module("./external-api", () => ({
  fetchData: mock(() => Promise.resolve({ data: "test" })),
}));
```

### 路径忽略模式

`pathIgnorePatterns` 使用 glob 模式完全从测试发现中排除文件和目录。与仅影响覆盖率报告的 `coveragePathIgnorePatterns` 不同，`pathIgnorePatterns` 可防止匹配路径被发现并作为测试运行。

当你的项目包含子模块、供应商代码或其他包含你不想让 `bun test` 捕获的 `*.test.ts` 文件的目录时使用。

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
# 单个模式
pathIgnorePatterns = "vendor/**"

# 多个模式
pathIgnorePatterns = [
  "vendor/**",
  "submodules/**",
  "fixtures/**"
]
```

这等同于在命令行中使用 `--path-ignore-patterns`：

```bash terminal icon="terminal" theme={null}
bun test --path-ignore-patterns 'vendor/**' --path-ignore-patterns 'fixtures/**'
```

Bun 会在扫描时剪除匹配某个模式的目录，并且从不遍历其内容，因此忽略大型目录树成本很低。

#### 常见用例

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
pathIgnorePatterns = [
  # 带有自己测试套件的 Git 子模块
  "submodules/**",

  # 供应商代码依赖
  "vendor/**",
  "third-party/**",

  # 看起来像测试但不是测试的测试夹具
  "fixtures/**",
  "**/test-data/**",

  # 要单独运行的集成/E2E 测试
  "**/integration/**",
  "e2e/**"
]
```

<Note>
  命令行的 `--path-ignore-patterns` 标志会完全覆盖 `bunfig.toml` 中的值——两者不会合并。
</Note>

## 报告器

### JUnit 报告器

直接在配置文件中配置 JUnit 报告器输出文件路径：

```toml title="bunfig.toml" icon="settings" theme={null}
[test.reporter]
junit = "path/to/junit.xml"  # JUnit XML 报告的输出路径
```

这补充了 `--reporter=junit` 和 `--reporter-outfile` CLI 标志：

```bash terminal icon="terminal" theme={null}
# 等效的命令行用法
bun test --reporter=junit --reporter-outfile=./junit.xml
```

#### 多个报告器

你可以同时使用多个报告器：

```bash terminal icon="terminal" theme={null}
# CLI 方式
bun test --reporter=junit --reporter-outfile=./junit.xml

# 配置文件方式
```

```toml title="bunfig.toml" icon="settings" theme={null}
[test.reporter]
junit = "./reports/junit.xml"

[test]
# 同时启用覆盖率报告
coverage = true
coverageReporter = ["text", "lcov"]
```

## 内存使用

### 小内存模式

为测试运行器专门启用 `--smol` 内存节省模式：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
smol = true  # 减少测试运行期间的内存使用
```

这等同于在命令行中使用 `--smol` 标志：

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

`smol` 模式通过以下方式减少内存使用：

* 减少 JavaScript 堆使用的内存
* 更积极地触发垃圾回收
* 在可能的情况下减少缓冲区大小

在内存受限的环境中使用它，例如 CI 运行器或大型测试套件。

## 测试执行

### concurrentTestGlob

运行与 glob 模式匹配的测试文件，并在其中启用并发测试执行。

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
concurrentTestGlob = "**/concurrent-*.test.ts"  # 匹配此模式的文件并发运行
```

匹配该模式的测试文件的行为就像传递了 `--concurrent` 标志一样：这些文件中的每个测试都并发运行。使用此选项逐步将测试套件迁移到并发执行，或让一种测试（比如集成测试）并发运行，而其余测试保持顺序执行。

`--concurrent` CLI 标志会覆盖此设置，强制所有测试并发运行，无论 glob 模式如何。

#### randomize

以随机顺序运行测试，以识别具有隐藏依赖关系的测试：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
randomize = true
```

#### seed

指定用于可重现的随机测试顺序的种子。需要 `randomize = true`：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
randomize = true
seed = 2444615283
```

#### retry

所有测试的默认重试次数。Bun 会重试失败的测试最多此次数。每个测试的 `{ retry: N }` 会覆盖此值。默认为 `0`（不重试）。

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
retry = 3
```

`--retry` CLI 标志会覆盖此设置。

#### rerunEach

多次重新运行每个测试文件以识别不稳定的测试：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
rerunEach = 3
```

## 覆盖率选项

### 基本覆盖率设置

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
# 默认启用覆盖率
coverage = true

# 设置覆盖率报告器
coverageReporter = ["text", "lcov"]

# 设置覆盖率输出目录
coverageDir = "./coverage"
```

### 跳过测试文件的覆盖率

从覆盖率报告中排除匹配测试模式的文件（例如 `*.test.ts`）：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
coverageSkipTestFiles = true  # 从覆盖率报告中排除测试文件
```

### 覆盖率阈值

将覆盖率阈值指定为单个数字或具有每个指标阈值的对象：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
# 简单阈值——适用于行、函数和语句
coverageThreshold = 0.8

# 详细阈值
coverageThreshold = { lines = 0.9, functions = 0.8, statements = 0.85 }
```

设置任一阈值都会启用 `fail_on_low_coverage`，如果覆盖率低于阈值，则导致测试运行失败。

#### 阈值示例

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
# 整体要求 90% 的覆盖率
coverageThreshold = 0.9

# 不同指标的不同要求
coverageThreshold = {
  lines = 0.85,      # 85% 行覆盖率
  functions = 0.90,  # 90% 函数覆盖率
  statements = 0.80  # 80% 语句覆盖率
}
```

### 覆盖率路径忽略模式

使用 glob 模式从覆盖率报告中排除特定文件或文件模式：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
# 单个模式
coveragePathIgnorePatterns = "**/*.spec.ts"

# 多个模式
coveragePathIgnorePatterns = [
  "**/*.spec.ts",
  "**/*.test.ts",
  "src/utils/**",
  "*.config.js",
  "generated/**",
  "vendor/**"
]
```

匹配任一模式的文件将从覆盖率计算和报告中排除。参见[代码覆盖率](/test/code-coverage)。

#### 常见忽略模式

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
coveragePathIgnorePatterns = [
  # 测试文件
  "**/*.test.ts",
  "**/*.spec.ts",
  "**/*.e2e.ts",

  # 配置文件
  "*.config.js",
  "*.config.ts",
  "webpack.config.*",
  "vite.config.*",

  # 构建输出
  "dist/**",
  "build/**",
  ".next/**",

  # 生成的代码
  "generated/**",
  "**/*.generated.ts",

  # 供应商/第三方代码
  "vendor/**",
  "third-party/**",

  # 不需要测试的工具函数
  "src/utils/constants.ts",
  "src/types/**"
]
```

### 源码映射处理

Bun 转译每个文件，因此覆盖率结果在报告之前会通过源码映射。`coverageIgnoreSourcemaps` 可退出此行为，但结果会令人困惑：在转译期间，Bun 可能会移动代码和重命名变量。此选项主要用于调试覆盖问题。

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
coverageIgnoreSourcemaps = true  # 不为覆盖率分析使用源码映射
```

<Warning>
  使用此选项时，你可能需要在源文件顶部添加 `// @bun` 注释以退出转译过程。
</Warning>

## 安装设置继承

`bun test` 从 `bunfig.toml` 的 `[install]` 部分继承网络和安装配置（如 `registry`、`cafile`、`prefer` 和 `exact`）。如果你的测试在运行期间访问私有注册表或触发安装，这一点很重要。

```toml title="bunfig.toml" icon="settings" theme={null}
[install]
# 这些设置由 bun test 继承
registry = "https://npm.company.com/"
exact = true
prefer = "offline"

[test]
# 测试特定配置
coverage = true
```

## 环境变量

使用 `.env` 文件为测试设置环境变量，Bun 会自动从项目根目录加载这些文件。对于测试特定的变量，创建一个 `.env.test` 文件，`bun test` 会自动加载它：

```ini title=".env.test" icon="settings" theme={null}
NODE_ENV=test
DATABASE_URL=postgresql://localhost:5432/test_db
LOG_LEVEL=error
```

## 完整配置示例

一个展示可用测试配置选项的示例：

```toml title="bunfig.toml" icon="settings" theme={null}
[install]
# 测试继承的安装设置
registry = "https://registry.npmjs.org/"
exact = true

[test]
# 测试发现
root = "src"
preload = ["./test-setup.ts", "./global-mocks.ts"]
pathIgnorePatterns = ["vendor/**", "submodules/**"]

# 执行设置
smol = true

# 覆盖率配置
coverage = true
coverageReporter = ["text", "lcov"]
coverageDir = "./coverage"
coverageThreshold = { lines = 0.85, functions = 0.90, statements = 0.80 }
coverageSkipTestFiles = true
coveragePathIgnorePatterns = [
  "**/*.spec.ts",
  "src/utils/**",
  "*.config.js",
  "generated/**"
]

# 高级覆盖率设置
coverageIgnoreSourcemaps = false

# 报告器配置
[test.reporter]
junit = "./reports/junit.xml"
```

## CLI 覆盖行为

命令行选项始终覆盖配置文件设置：

```toml title="bunfig.toml" icon="settings" theme={null}
[test]
coverage = false
```

```bash terminal icon="terminal" theme={null}
# 此 CLI 标志会覆盖配置文件
bun test --coverage
# 覆盖率将被启用
```
