Bun测试覆盖率管理 BunTestCoverage

Bun 测试覆盖率管理技能用于在 Bun 运行时中启用和配置代码覆盖率报告,支持设置覆盖率阈值、生成多种格式的报告(如 text、lcov、json),并集成到 CI/CD 流程中,帮助开发者确保代码质量和测试完整性。关键词:Bun, 测试覆盖率, 代码覆盖, 覆盖率报告, CI/CD, 阈值, LCOV, 自动化测试。

测试 0 次安装 0 次浏览 更新于 3/8/2026

name: Bun 测试覆盖率 description: 用于 Bun 的测试覆盖率,包括 --coverage 标志、lcov 报告、阈值和 CI 集成。 version: 1.0.0

Bun 测试覆盖率

Bun 内置了代码覆盖率报告功能,无需额外依赖。

启用覆盖率

# 启用覆盖率
bun test --coverage

# 带阈值(如果低于阈值则失败)
bun test --coverage --coverage-threshold 80

在 bunfig.toml 中配置

[test]
coverage = true
coverageThreshold = 0.8  # 最低 80%
coverageDir = "./coverage"

# 忽略的模式
coverageSkipTestFiles = true

覆盖率输出

------------------|---------|---------|-------------------
文件              | % 函数 | % 行   | 未覆盖的行号
------------------|---------|---------|-------------------
所有文件         |   85.71 |   89.23 |
 src/index.ts     |  100.00 |  100.00 |
 src/utils.ts     |   75.00 |   82.35 | 23-25, 41-43
 src/api.ts       |   80.00 |   85.00 | 67, 89-92
------------------|---------|---------|-------------------

覆盖率报告器

# 默认控制台输出
bun test --coverage

# 生成 lcov 报告
bun test --coverage --coverage-reporter=lcov

# 多个报告器
bun test --coverage --coverage-reporter=text --coverage-reporter=lcov

可用报告器

报告器 输出
text 控制台表格(默认)
lcov coverage/lcov.info 用于 CI 工具
json coverage/coverage.json

覆盖率阈值

设置最低覆盖率要求:

# 如果覆盖率 < 80% 则失败
bun test --coverage --coverage-threshold 80

# 在 bunfig.toml 中按指标设置阈值
[test]
coverage = true
coverageThreshold = {
  lines = 80,
  functions = 75,
  branches = 70
}

排除文件

[test]
coverage = true

# 从覆盖率中跳过测试文件
coverageSkipTestFiles = true

# 排除的模式
coverageIgnore = [
  "**/*.test.ts",
  "**/fixtures/**",
  "**/mocks/**"
]

CI 集成

GitHub Actions

- name: 运行带覆盖率的测试
  run: bun test --coverage --coverage-reporter=lcov

- name: 上传覆盖率到 Codecov
  uses: codecov/codecov-action@v5
  with:
    files: ./coverage/lcov.info

输出目录

# 自定义输出目录
bun test --coverage --coverage-dir=./reports/coverage

编程式覆盖率

import { test, expect } from "bun:test";

// 以编程方式获取覆盖率数据
const coverage = Bun.coverage;

// 测试完成后访问
process.on("exit", () => {
  console.log(coverage.getCoverageData());
});

常见错误

错误 原因 修复
Coverage threshold not met 覆盖率低于阈值 提高测试覆盖率
No coverage data 文件未被执行 检查测试是否包含文件
lcov not found 缺少报告器 添加 --coverage-reporter=lcov

最佳实践

  1. 设置现实阈值 - 从 60% 开始,逐步提高
  2. 排除生成文件 - 模拟文件、类型定义
  3. 关注关键路径 - 业务逻辑而非模板代码
  4. 在 CI 中运行 - 防止覆盖率退化

何时加载参考

加载 references/reporters.md 当:

  • 自定义报告器配置
  • CI/CD 集成细节
  • Codecov/Coveralls 设置