Bun

指南測試執行器

使用 Bun 測試執行器執行您的測試

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.jstest2.test.jstest3.test.js),每個檔案包含兩個測試 (addmultiply)。

bun test
bun test v1.2.5 (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.2.5 (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 標flag。

新增 -t add 將只會執行名稱中包含 "add" 的測試。這適用於使用 test 定義的測試名稱,或使用 describe 定義的測試套件名稱。

bun test -t add
bun test v1.2.5 (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]

請參閱文件 > 測試執行器,以取得關於測試執行器的完整文件。