Skip to content

Bun 有一個內置的 測試運行器,具有類似 Jest 的 expect API。


要使用它,請在項目目錄中運行 bun test 命令。測試運行器將遞歸搜索目錄中匹配以下模式的所有文件並執行其中包含的測試。

txt
*.test.{js|jsx|ts|tsx}
*_test.{js|jsx|ts|tsx}
*.spec.{js|jsx|ts|tsx}
*_spec.{js|jsx|ts|tsx}

以下是典型測試運行的輸出。在這種情況下,有三個測試文件(test.test.jstest2.test.jstest3.test.js),每個文件包含兩個測試(addmultiply)。

sh
bun test
txt
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。運行器將只執行路徑中包含該參數的文件。

sh
bun test test3
txt
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 分組到套件中。

ts
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 定義的測試套件名稱。

sh
bun test -t add
txt
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]

請參閱 文檔 > 測試運行器 獲取測試運行器的完整文檔。

Bun學習網由www.bunjs.com.cn整理維護