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.3.0 (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.3.0 (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.3.0 (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]

有關測試執行器的完整文件,請參閱 文件 > 測試執行器