Documentation Index
Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
Use this file to discover all available pages before exploring further.
Bun 内置了一个具有类似 Jest 的 expect API 的 测试运行器。
要使用它,请在项目目录中运行 bun test 命令。测试运行器会递归搜索目录中所有符合以下模式的文件,并执行其中包含的测试。
*.test.{js|jsx|ts|tsx}
*_test.{js|jsx|ts|tsx}
*.spec.{js|jsx|ts|tsx}
*_spec.{js|jsx|ts|tsx}
下面是一次典型测试运行的输出示例。在此案例中,有三个测试文件(test.test.js、test2.test.js 和 test3.test.js),每个文件包含两个测试(add 和 multiply)。
test.test.js:
✓ add [0.87ms]
✓ multiply [0.02ms]
test2.test.js:
✓ add [0.72ms]
✓ multiply [0.01ms]
test3.test.js:
✓ add [0.54ms]
✓ multiply [0.01ms]
6 pass
0 fail
6 expect() calls
Ran 6 tests across 3 files. [9.00ms]
若只想运行特定测试文件,请向 bun test 传递一个位置参数。运行器只会执行路径中包含该参数的文件。
test3.test.js:
✓ add [1.40ms]
✓ multiply [0.03ms]
2 pass
0 fail
2 expect() calls
Ran 2 tests across 1 files. [15.00ms]
所有测试都有一个名称,通过 test 函数的第一个参数定义。测试也可以使用 describe 进行分组。
import { test, expect, describe } from "bun:test";
describe("math", () => {
test("add", () => {
expect(2 + 2).toEqual(4);
});
test("multiply", () => {
expect(2 * 2).toEqual(4);
});
});
要根据名称过滤执行的测试,请使用 -t/--test-name-pattern 标志。
添加 -t add 将只运行名称中带有 “add” 的测试。此选项适用于通过 test 定义的测试名或通过 describe 定义的测试套件名。
test.test.js:
✓ add [1.79ms]
» multiply
test2.test.js:
✓ add [2.30ms]
» multiply
test3.test.js:
✓ add [0.32ms]
» multiply
3 pass
3 skip
0 fail
3 expect() calls
Ran 6 tests across 3 files. [59.00ms]
完整的测试运行器文档请参阅 文档 > 测试运行器。