Bun

测试配置

通过 bunfig.toml 文件和命令行选项配置 bun test。本页档介绍了 bun test 可用的配置选项。

bunfig.toml 选项

您可以通过在 bunfig.toml 文件中添加 [test] 部分来配置 bun test 的行为。

[test]
# Options go here

测试发现

root

root 选项指定了测试发现的根目录,它会覆盖从项目根目录扫描的默认行为。

[test]
root = "src"  # Only scan for tests in the src directory

报告器

reporter.junit

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

[test.reporter]
junit = "path/to/junit.xml"  # Output path for JUnit XML report

这补充了 --reporter=junit--reporter-outfile 命令行标志。

内存使用

smol

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

[test]
smol = true  # Reduce memory usage during test runs

这相当于在命令行中使用 --smol 标志。

测试执行

concurrentTestGlob

自动运行与 glob 模式匹配的测试文件,并启用并发测试执行。这对于逐步将测试套件迁移到并发执行或并发运行特定测试类型非常有用。

[test]
concurrentTestGlob = "**/concurrent-*.test.ts"  # Run files matching this pattern concurrently

匹配此模式的测试文件将像传递了 --concurrent 标志一样,在这些文件中并发运行所有测试。这允许您:

  • 逐步将您的测试套件迁移到并发执行
  • 并发运行集成测试,同时保持单元测试按顺序执行
  • 将快速并发测试与需要顺序执行的测试分开

当指定 --concurrent CLI 标志时,它将覆盖此设置,强制所有测试并发运行,无论 glob 模式如何。

randomize

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

[test]
randomize = true

seed

指定一个种子以实现可重现的随机测试顺序。需要 randomize = true

[test]
randomize = true
seed = 2444615283

rerunEach

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

[test]
rerunEach = 3

覆盖率选项

除了覆盖率文档中记录的选项外,还提供以下选项

coverageSkipTestFiles

从覆盖率报告中排除匹配测试模式(例如,*.test.ts)的文件

[test]
coverageSkipTestFiles = true  # Exclude test files from coverage reports

coverageThreshold(对象形式)

覆盖率阈值可以指定为数字(如覆盖率文档所示)或带有特定阈值的对象

[test]
# Set specific thresholds for different coverage metrics
coverageThreshold = { lines = 0.9, functions = 0.8, statements = 0.85 }

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

coveragePathIgnorePatterns

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

[test]
# Single pattern
coveragePathIgnorePatterns = "**/*.spec.ts"

# Multiple patterns
coveragePathIgnorePatterns = [
  "**/*.spec.ts",
  "**/*.test.ts",
  "src/utils/**",
  "*.config.js"
]

匹配任何这些模式的文件将从覆盖率计算和报告中排除。有关更多详细信息和示例,请参阅覆盖率文档

coverageIgnoreSourcemaps

在内部,Bun 会转译每个文件。这意味着代码覆盖率在报告之前也必须经过源映射。我们将此作为一个标志公开,允许您选择退出此行为,但这会令人困惑,因为在转译过程中,Bun 可能会移动代码并更改变量名。此选项主要用于调试覆盖率问题。

[test]
coverageIgnoreSourcemaps = true  # Don't use sourcemaps for coverage analysis

使用此选项时,您可能希望在源文件顶部添加 // @bun 注释以选择退出转译过程。

安装设置继承

bun test 命令从 bunfig.toml 的 [install] 部分继承相关的网络和安装配置(registry、cafile、prefer、exact 等)。如果测试需要与私有注册表交互或在测试运行期间需要特定的安装行为,这一点很重要。