> ## 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 test` 以人类可读的格式将结果输出到控制台：

```sh terminal icon="terminal" theme={null}
test/package-json-lint.test.ts:
✓ test/package.json [0.88ms]
✓ test/js/third_party/grpc-js/package.json [0.18ms]
✓ test/js/third_party/svelte/package.json [0.21ms]
✓ test/js/third_party/express/package.json [1.05ms]

 4 pass
 0 fail
 4 expect() calls
Ran 4 tests in 1.44ms
```

当终端不支持颜色时，输出会避免非 ASCII 字符：

```sh terminal icon="terminal" theme={null}
test/package-json-lint.test.ts:
(pass) test/package.json [0.48ms]
(pass) test/js/third_party/grpc-js/package.json [0.10ms]
(pass) test/js/third_party/svelte/package.json [0.04ms]
(pass) test/js/third_party/express/package.json [0.04ms]

 4 pass
 0 fail
 4 expect() calls
Ran 4 tests across 1 files. [0.66ms]
```

### 点报告器

点报告器用 `.` 表示通过的测试，并打印失败的完整错误详情，适用于大型测试套件。

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

### JUnit XML 报告器

对于 CI/CD 环境，Bun 可以生成 JUnit XML 报告，这是一种广泛采用的测试结果格式，许多 CI/CD 系统都可以解析，包括 GitLab 和 Jenkins。

#### 使用 JUnit 报告器

要生成 JUnit XML 报告，请使用 `--reporter=junit` 标志和 `--reporter-outfile` 来指定输出文件：

```sh terminal icon="terminal" theme={null}
bun test --reporter=junit --reporter-outfile=./junit.xml
```

控制台输出不变；Bun 在测试运行结束时将 JUnit XML 报告写入指定路径。

#### 通过 bunfig.toml 配置

你也可以在 `bunfig.toml` 中配置 JUnit 报告器：

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

#### JUnit 报告中的环境变量

JUnit 报告器在 XML 输出中包含环境信息作为 `<properties>`，因此你可以知道测试运行是针对哪个环境和提交。

它会在可用时包含以下环境变量：

| 环境变量                                                                 | 属性名        | 描述        |
| -------------------------------------------------------------------- | ---------- | --------- |
| `GITHUB_RUN_ID`、`GITHUB_SERVER_URL`、`GITHUB_REPOSITORY`、`CI_JOB_URL` | `ci`       | CI 构建信息   |
| `GITHUB_SHA`、`CI_COMMIT_SHA`、`GIT_SHA`                               | `commit`   | Git 提交标识符 |
| 系统主机名                                                                | `hostname` | 机器主机名     |

#### 当前限制

JUnit 报告器不包括：

* 来自各个测试的 `stdout` 和 `stderr` 输出
* 每个测试用例的精确时间戳字段

### GitHub Actions 报告器

`bun test` 会检测何时在 GitHub Actions 中运行，并直接将 GitHub Actions 注释输出到控制台。除了安装 Bun 并运行 `bun test` 外，无需任何配置。

有关 GitHub Actions 工作流的示例，请参见[CI/CD 集成](/pm/cli/install#ci%2Fcd)。

***

## 自定义报告器

你可以使用 Bun 对 WebKit Inspector 协议的测试特定扩展来实现自定义测试报告器，这些扩展会实时报告有关测试执行的详细信息。

### 用于测试的 Inspector 协议

Bun 用两个自定义域扩展了标准的 WebKit Inspector 协议：

1. **TestReporter**：报告测试发现、执行开始和完成事件
2. **LifecycleReporter**：报告测试执行期间的错误和异常

### 关键事件

自定义报告器可以监听以下事件：

* `TestReporter.found`：发现测试时触发
* `TestReporter.start`：测试开始运行时触发
* `TestReporter.end`：测试完成时触发
* `Console.messageAdded`：测试期间发生控制台输出时触发
* `LifecycleReporter.error`：发生错误或异常时触发
