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)。
bun testbun test v1.3.0 (9c68abdb)
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。运行器将仅执行路径中包含该参数的文件。
bun test test3bun test v1.3.0 (9c68abdb)
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 定义的测试套件名称。
bun test -t addbun test v1.3.0 (9c68abdb)
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]有关测试运行器的完整文档,请参阅 文档 > 测试运行器。