SuperAPI AI 工具集

bun-test-basics

测试与质量

查看项目

更新于 10-15 13:41

技能介绍

Bun Test Basics 介绍 Bun 内置测试运行器的基本用法。Bun 自带一个快速、兼容 Jest 的测试运行器,测试运行在 Bun 运行时上,原生支持 TypeScript/JSX。

【快速开始】 运行全部测试:bun test 运行指定文件:bun test ./test/math.test.ts 按名称模式筛选:bun test --test-name-pattern "addition"

【编写测试】 从 bun:test 导入 test、expect、describe。 基本测试:test("2 + 2", () => { expect(2 + 2).toBe(4); }) 使用 describe 分组:describe("math", () => { ... }),其中可嵌套 test("addition")、test("subtraction") 等。

【测试文件匹配规则】 Bun 自动发现以下命名规则的文件: *.test.{js|jsx|ts|tsx} *_test.{js|jsx|ts|tsx} *.spec.{js|jsx|ts|tsx} *_spec.{js|jsx|ts|tsx}

【测试修饰符】 test.skip("not ready", ...):跳过测试,不运行。 test.only("focus on this", ...):只运行该测试,其他测试不运行。注意:在 Bun 1.3+ 中,当文件使用 test.only 时,CI 环境下 bun test 会以非零状态退出;仅用于本地调试,不要提交。 test.todo("implement later"):占位待实现的测试。 test.failing("known bug", ...):预期会失败,抛出异常属于预期结果。

【参数化测试】 test.each([...]) 支持数组形式与对象形式。数组示例:test.each([[1,1,2],[2,2,4],[3,3,6]])("add(%i, %i) = %i", (a, b, expected) => { expect(a + b).toBe(expected); })。对象示例使用 $a、$b、$expected 模板占位。

【并发测试】 test.concurrent("async test 1", async () => { ... }):并行运行测试。 test.serial("must run alone", ...):在使用 --concurrent 时强制顺序运行。

【常用匹配器】 相等:toBe(严格相等)、toEqual(深相等)、toStrictEqual(严格相等并校验类型)。 真值:toBeTruthy、toBeFalsy、toBeNull、toBeDefined、toBeUndefined。 数字:toBeGreaterThan、toBeGreaterThanOrEqual、toBeLessThan、toBeCloseTo(浮点数)。 字符串:toMatch、toContain、toStartWith、toEndWith。 数组:toContain、toContainEqual、toHaveLength。 对象:toHaveProperty、toMatchObject。 异常:toThrow。 异步:resolves、rejects。 取反:not。

【CLI 选项】 --timeout:每个测试的超时时间,默认 5000ms,例如 bun test --timeout 20。 --bail 或 --bail=10:失败 N 次后中止。 --watch:监视模式。 --randomize、--seed 12345:随机顺序与随机种子。 --concurrent、--concurrent --max-concurrency 4:并发执行与最大并发数。 -t "pattern":按名称过滤。

【输出报告器】 --dots:紧凑的点输出。 --reporter=junit --reporter-outfile=./results.xml:JUnit XML 报告,适用于 CI/CD。

【常见错误】 测试超时:测试超过 5s,可用 --timeout 或优化测试。 未找到测试:文件命名模式错误,检查文件命名。 expect is not defined:缺少导入,从 bun:test 导入。 断言失败:测试失败,检查预期值与实际值。

【参考资料加载时机】 当需要完整匹配器参考或自定义匹配器模式时,加载 references/matchers.md。 当需要完整 CLI 标志参考或高级执行选项时,加载 references/cli-options.md。

【限制】 本资料仅涉及 bun:test 的语法与基础用法,未提供收费、价格、平台或其他未列出的功能信息。