使用 Bun 测试运行器运行测试
Bun 内置了一个具有类似 Jest 的 expect API 的 测试运行器。
要使用它,请在项目目录中运行 bun test。测试运行器会递归搜索匹配以下模式的文件,并运行其中包含的测试。
File
*.test.{js|jsx|ts|tsx|mjs|cjs|mts|cts}
*_test.{js|jsx|ts|tsx|mjs|cjs|mts|cts}
*.spec.{js|jsx|ts|tsx|mjs|cjs|mts|cts}
*_spec.{js|jsx|ts|tsx|mjs|cjs|mts|cts}
以下是一次典型运行的输出:三个测试文件(test.test.js、test2.test.js 和 test3.test.js),每个文件包含两个测试(add 和 multiply)。
terminal
bun test
Text
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 传入一个位置参数。运行器只会执行路径中包含该参数的文件。
terminal
bun test test3
Text
test3.test.js:
✓ add [1.40ms]
✓ multiply [0.03ms]
2 pass
0 fail
2 expect() calls
Ran 2 tests across 1 file. [15.00ms]
每个测试都有一个名称:它是 test 函数的第一个参数。你也可以使用 describe 将测试分组成测试套件。
TypeScript
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 定义的测试套件名称。
terminal
bun test -t add
Text
test.test.js:
✓ add [1.79ms]
test2.test.js:
✓ add [2.30ms]
test3.test.js:
✓ add [0.32ms]
3 pass
3 filtered out
0 fail
3 expect() calls
Ran 3 tests across 3 files. [59.00ms]
请参阅 bun test。