关于 bun-test-coverage
面向 Bun 测试开发者的代码覆盖率技能,介绍内置覆盖率报告、阈值、报告格式和 CI 配置。
主要功能
- 01使用命令行启用覆盖率
- 02设置覆盖率阈值
- 03生成文本、lcov 和 JSON 报告
- 04配置排除文件与输出目录
- 05通过 Bun.coverage 获取数据
适用场景
- 01在 CI 中生成 lcov 报告
- 02低于覆盖率门槛时让测试失败
- 03查看未覆盖代码行并调整测试
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill bun-test-coverage安装后在 Claude Code 中输入/bun-test-coverage确认已加载。
详细介绍
Bun 测试覆盖率
Bun 内置代码覆盖率报告,无需额外依赖。
启用覆盖率
# Enable coverage
bun test --coverage
# With threshold (fail if below)
bun test --coverage --coverage-threshold 80
在 bunfig.toml 中配置
[test]
coverage = true
coverageThreshold = 0.8 # 80% minimum
coverageDir = "./coverage"
# Patterns to ignore
coverageSkipTestFiles = true
覆盖率输出
------------------|---------|---------|-------------------
File | % Funcs | % Lines | Uncovered Line #s
------------------|---------|---------|-------------------
All files | 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
------------------|---------|---------|-------------------
覆盖率报告器
# Default console output
bun test --coverage
# Generate lcov report
bun test --coverage --coverage-reporter=lcov
# Multiple reporters
bun test --coverage --coverage-reporter=text --coverage-reporter=lcov
可用的报告器
| 报告器 | 输出 |
|---|---|
text | 控制台表格(默认) |
lcov | 供 CI 工具使用的 coverage/lcov.info |
json | coverage/coverage.json |
覆盖率阈值
设置最低覆盖率要求:
# Fail if coverage < 80%
bun test --coverage --coverage-threshold 80
# Per-metric thresholds in bunfig.toml
[test]
coverage = true
coverageThreshold = {
lines = 80,
functions = 75,
branches = 70
}
排除文件
[test]
coverage = true
# Skip test files from coverage
coverageSkipTestFiles = true
# Patterns to exclude
coverageIgnore = [
"**/*.test.ts",
"**/fixtures/**",
"**/mocks/**"
]
CI 集成
GitHub Actions
- name: Run tests with coverage
run: bun test --coverage --coverage-reporter=lcov
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
with:
files: ./coverage/lcov.info
输出目录
# Custom output directory
bun test --coverage --coverage-dir=./reports/coverage
编程方式获取覆盖率
import { test, expect } from "bun:test";
// Get coverage data programmatically
const coverage = Bun.coverage;
// Access after tests complete
process.on("exit", () => {
console.log(coverage.getCoverageData());
});
常见错误
| 错误 | 原因 | 修复方法 |
|---|---|---|
Coverage threshold not met | 覆盖率低于阈值 | 提高测试覆盖率 |
No coverage data | 未执行文件 | 检查测试是否包含该文件 |
lcov not found | 缺少报告器 | 添加 --coverage-reporter=lcov |
最佳实践
- 设置切合实际的阈值 - 从 60% 开始,逐步提高
- 排除生成的文件 - 模拟文件、类型定义
- 关注关键路径 - 优先覆盖业务逻辑,而非样板代码
- 在 CI 中运行 - 防止覆盖率回退
何时加载参考资料
在以下情况下加载 references/reporters.md:
- 自定义报告器配置
- CI/CD 集成详情
- Codecov/Coveralls 设置
评论
支持 Markdown