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 test
bun test v1.x (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 test3
bun test v1.x (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 add
bun test v1.x (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]
請參閱 文件 > 測試執行器,以取得測試執行器的完整文件。