使用 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。