Bun 內建了一個快速、Jest 相容的測試執行器。測試使用 Bun 執行時執行,並支援以下功能。
- TypeScript 和 JSX
- 生命週期鉤子
- 快照測試
- UI 和 DOM 測試
- 使用
--watch的觀察模式 - 使用
--preload的指令碼預載入
Bun 的目標是與 Jest 相容,但並非所有功能都已實現。要跟蹤相容性,請參閱此跟蹤問題。
執行測試
bun test測試以 JavaScript 或 TypeScript 編寫,使用類似 Jest 的 API。有關完整文件,請參閱編寫測試。
import { expect, test } from "bun:test";
test("2 + 2", () => {
expect(2 + 2).toBe(4);
});
執行器遞迴搜尋工作目錄中與以下模式匹配的檔案
*.test.{js|jsx|ts|tsx}*_test.{js|jsx|ts|tsx}*.spec.{js|jsx|ts|tsx}*_spec.{js|jsx|ts|tsx}
您可以透過向 bun test 傳遞額外的位置引數來篩選要執行的_測試檔案_集。任何路徑與其中一個篩選器匹配的測試檔案都將執行。通常,這些篩選器將是檔案或目錄名稱;目前不支援 glob 模式。
bun test <filter> <filter> ...要按_測試名稱_篩選,請使用 -t/--test-name-pattern 標誌。
# run all tests or test suites with "addition" in the namebun test --test-name-pattern addition當沒有測試匹配篩選器時,bun test 以程式碼 1 退出。
要在測試執行器中執行特定檔案,請確保路徑以 ./ 或 / 開頭,以將其與篩選器名稱區分開來。
bun test ./test/specific-file.test.ts測試執行器在單個程序中執行所有測試。它載入所有 --preload 指令碼(有關詳細資訊,請參閱生命週期),然後執行所有測試。如果測試失敗,測試執行器將以非零退出程式碼退出。
CI/CD 整合
bun test 支援各種 CI/CD 整合。
GitHub Actions
bun test 自動檢測它是否在 GitHub Actions 中執行,並將直接向控制檯輸出 GitHub Actions 註釋。
除了在工作流中安裝 bun 並執行 bun test 之外,不需要其他配置。
如何在 GitHub Actions 工作流中安裝 bun
要在 GitHub Actions 工作流中使用 bun test,請新增以下步驟
jobs:
build:
name: build-app
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install bun
uses: oven-sh/setup-bun@v2
- name: Install dependencies # (assuming your project has dependencies)
run: bun install # You can use npm/yarn/pnpm instead if you prefer
- name: Run tests
run: bun test
從那裡,您將獲得 GitHub Actions 註釋。
JUnit XML 報告 (GitLab 等)
要將 bun test 與 JUnit XML 報告器一起使用,您可以將 --reporter=junit 與 --reporter-outfile 結合使用。
bun test --reporter=junit --reporter-outfile=./bun.xml這將像往常一樣繼續輸出到 stdout/stderr,並在測試執行結束時將 JUnit XML 報告寫入給定路徑。
JUnit XML 是一種在 CI/CD 流水線中報告測試結果的流行格式。
超時
使用 --timeout 標誌指定_每個測試_的超時時間(毫秒)。如果測試超時,它將被標記為失敗。預設值為 5000。
# default value is 5000bun test --timeout 20併發測試執行
預設情況下,Bun 在每個測試檔案中按順序執行所有測試。您可以啟用併發執行以並行執行非同步測試,從而顯著加快具有獨立測試的測試套件。
--concurrent 標誌
使用 --concurrent 標誌在其各自的檔案中併發執行所有測試
bun test --concurrent啟用此標誌後,除非明確標記為 test.serial,否則所有測試都將並行執行。
--max-concurrency 標誌
使用 --max-concurrency 標誌控制同時執行的最大測試數量
# Limit to 4 concurrent testsbun test --concurrent --max-concurrency 4
# Default: 20bun test --concurrent這有助於在執行許多併發測試時防止資源耗盡。預設值為 20。
test.concurrent
標記單個測試以併發執行,即使未使用 --concurrent 標誌
import { test, expect } from "bun:test";
// These tests run in parallel with each other
test.concurrent("concurrent test 1", async () => {
await fetch("/api/endpoint1");
expect(true).toBe(true);
});
test.concurrent("concurrent test 2", async () => {
await fetch("/api/endpoint2");
expect(true).toBe(true);
});
// This test runs sequentially
test("sequential test", () => {
expect(1 + 1).toBe(2);
});
test.serial
即使啟用了 --concurrent 標誌,也強制測試按順序執行
import { test, expect } from "bun:test";
let sharedState = 0;
// These tests must run in order
test.serial("first serial test", () => {
sharedState = 1;
expect(sharedState).toBe(1);
});
test.serial("second serial test", () => {
// Depends on the previous test
expect(sharedState).toBe(1);
sharedState = 2;
});
// This test can run concurrently if --concurrent is enabled
test("independent test", () => {
expect(true).toBe(true);
});
// Chaining test qualifiers
test.failing.each([1, 2, 3])("chained qualifiers %d", input => {
expect(input).toBe(0); // This test is expected to fail for each input
});
重新執行測試
使用 --rerun-each 標誌多次執行每個測試。這對於檢測不穩定或非確定性測試失敗很有用。
bun test --rerun-each 100隨機化測試執行順序
使用 --randomize 標誌以隨機順序執行測試。這有助於檢測依賴於共享狀態或執行順序的測試。
bun test --randomize使用 --randomize 時,用於隨機化的種子將顯示在測試摘要中
bun test --randomize# ... test output ...
--seed=12345
2 pass
8 fail
Ran 10 tests across 2 files. [50.00ms]使用 --seed 可重現隨機順序
使用 --seed 標誌為隨機化指定一個種子。這允許您在除錯依賴於順序的失敗時重現相同的測試順序。
# Reproduce a previous randomized runbun test --seed 123456--seed 標誌意味著 --randomize,因此您無需同時指定兩者。使用相同的種子值將始終產生相同的測試執行順序,從而更容易除錯由測試相互依賴性引起的間歇性失敗。
使用 --bail 退出
使用 --bail 標誌在預定數量的測試失敗後提前中止測試執行。預設情況下,Bun 將執行所有測試並報告所有失敗,但有時在 CI 環境中,為了減少 CPU 使用率,提前終止是更可取的。
# bail after 1 failurebun test --bail
# bail after 10 failurebun test --bail=10Watch 模式
與 bun run 類似,您可以將 --watch 標誌傳遞給 bun test 以監視更改並重新執行測試。
bun test --watch生命週期鉤子
Bun 支援以下生命週期鉤子
| 鉤子 | 描述 |
|---|---|
beforeAll | 在所有測試執行之前執行一次。 |
beforeEach | 在每個測試執行之前執行。 |
afterEach | 在每個測試執行之後執行。 |
afterAll | 在所有測試執行之後執行一次。 |
這些鉤子可以在測試檔案中定義,也可以在單獨的檔案中定義,並使用 --preload 標誌進行預載入。
$ bun test --preload ./setup.ts
有關完整文件,請參閱測試 > 生命週期。
模擬
使用 mock 函式建立模擬函式。
import { test, expect, mock } from "bun:test";
const random = mock(() => Math.random());
test("random", () => {
const val = random();
expect(val).toBeGreaterThan(0);
expect(random).toHaveBeenCalled();
expect(random).toHaveBeenCalledTimes(1);
});
或者,您可以使用 jest.fn(),它的行為完全相同。
import { test, expect, mock } from "bun:test";
import { test, expect, jest } from "bun:test";
const random = mock(() => Math.random());
const random = jest.fn(() => Math.random());有關完整文件,請參閱測試 > 模擬。
快照測試
bun test 支援快照。
// example usage of toMatchSnapshot
import { test, expect } from "bun:test";
test("snapshot", () => {
expect({ a: 1 }).toMatchSnapshot();
});
要更新快照,請使用 --update-snapshots 標誌。
bun test --update-snapshots有關完整文件,請參閱測試 > 快照。
UI & DOM 測試
Bun 相容流行的 UI 測試庫
有關完整文件,請參閱測試 > DOM 測試。
效能
Bun 的測試執行器速度很快。

AI 代理整合
將 Bun 的測試執行器與 AI 編碼助手一起使用時,您可以啟用更安靜的輸出,以提高可讀性並減少上下文噪音。此功能最大程度地減少了測試輸出的冗長性,同時保留了必要的失敗資訊。
環境變數
設定以下任何環境變數以啟用 AI 友好的輸出
CLAUDECODE=1- 用於 Claude CodeREPL_ID=1- 用於 ReplitAGENT=1- 通用 AI 代理標誌
行為
當檢測到 AI 代理環境時
- 僅詳細顯示測試失敗
- 透過、跳過和待辦測試指示器被隱藏
- 摘要統計資料保持不變
# Example: Enable quiet output for Claude CodeCLAUDECODE=1 bun test
# Still shows failures and summary, but hides verbose passing test output此功能在 AI 輔助開發工作流中特別有用,其中減少輸出冗長性可以提高上下文效率,同時保持對測試失敗的可見性。