Bun

測試

Bun 內建了一個快速、Jest 相容的測試執行器。測試使用 Bun 執行時執行,並支援以下功能。

  • TypeScript 和 JSX
  • 生命週期鉤子
  • 快照測試
  • UI 和 DOM 測試
  • 使用 --watch 的觀察模式
  • 使用 --preload 的指令碼預載入

Bun 的目標是與 Jest 相容,但並非所有功能都已實現。要跟蹤相容性,請參閱此跟蹤問題

執行測試

bun test

測試以 JavaScript 或 TypeScript 編寫,使用類似 Jest 的 API。有關完整文件,請參閱編寫測試

math.test.ts
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 name
bun 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 5000
bun test --timeout 20

併發測試執行

預設情況下,Bun 在每個測試檔案中按順序執行所有測試。您可以啟用併發執行以並行執行非同步測試,從而顯著加快具有獨立測試的測試套件。

--concurrent 標誌

使用 --concurrent 標誌在其各自的檔案中併發執行所有測試

bun test --concurrent

啟用此標誌後,除非明確標記為 test.serial,否則所有測試都將並行執行。

--max-concurrency 標誌

使用 --max-concurrency 標誌控制同時執行的最大測試數量

# Limit to 4 concurrent tests
bun test --concurrent --max-concurrency 4

# Default: 20
bun 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 run
bun test --seed 123456

--seed 標誌意味著 --randomize,因此您無需同時指定兩者。使用相同的種子值將始終產生相同的測試執行順序,從而更容易除錯由測試相互依賴性引起的間歇性失敗。

使用 --bail 退出

使用 --bail 標誌在預定數量的測試失敗後提前中止測試執行。預設情況下,Bun 將執行所有測試並報告所有失敗,但有時在 CI 環境中,為了減少 CPU 使用率,提前終止是更可取的。

# bail after 1 failure
bun test --bail

# bail after 10 failure
bun test --bail=10

Watch 模式

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 的測試執行器速度很快。

執行 266 個 React SSR 測試比 Jest 列印其版本號還要快。

AI 代理整合

將 Bun 的測試執行器與 AI 編碼助手一起使用時,您可以啟用更安靜的輸出,以提高可讀性並減少上下文噪音。此功能最大程度地減少了測試輸出的冗長性,同時保留了必要的失敗資訊。

環境變數

設定以下任何環境變數以啟用 AI 友好的輸出

  • CLAUDECODE=1 - 用於 Claude Code
  • REPL_ID=1 - 用於 Replit
  • AGENT=1 - 通用 AI 代理標誌

行為

當檢測到 AI 代理環境時

  • 僅詳細顯示測試失敗
  • 透過、跳過和待辦測試指示器被隱藏
  • 摘要統計資料保持不變
# Example: Enable quiet output for Claude Code
CLAUDECODE=1 bun test

# Still shows failures and summary, but hides verbose passing test output

此功能在 AI 輔助開發工作流中特別有用,其中減少輸出冗長性可以提高上下文效率,同時保持對測試失敗的可見性。

CLI 用法

$bun test <模式>

Flags

執行控制

--timeout=<值>
設定每個測試的超時時間(毫秒),預設值為 5000。
--rerun-each=<值>
每個測試檔案重新執行 <NUMBER> 次,有助於捕獲某些錯誤
--concurrent
將所有測試視為 `test.concurrent()` 測試
--randomize
以隨機順序執行測試
--seed=<值>
設定測試隨機化的隨機種子
--bail=<值>
在 <NUMBER> 次失敗後退出測試套件。如果您未指定數字,則預設為 1。
--max-concurrency=<值>
同時執行的最大併發測試數量。預設值為 20。

測試篩選

--todo
包含標記為 "test.todo()" 的測試
-t,--test-name-pattern=<值>
僅執行名稱與給定正則表示式匹配的測試。

報告

--reporter=<值>
測試輸出報告器格式。可用:'junit' (需要 --reporter-outfile),'dots'。預設值:控制檯輸出。
--reporter-outfile=<值>
報告器格式的輸出檔案路徑(--reporter 必需)。
--dots
啟用點報告器。--reporter=dots 的簡寫。

覆蓋率

--coverage
生成覆蓋率配置檔案
--coverage-reporter=<值>
以“text”和/或“lcov”格式報告覆蓋率。預設為“text”。
--coverage-dir=<值>
覆蓋率檔案目錄。預設為“coverage”。

快照

-u,--update-snapshots
更新快照檔案

Examples

執行所有測試檔案
bun test
執行檔名中包含“foo”或“bar”的所有測試檔案
bun test foo bar
執行所有測試檔案,僅包含名稱中包含“baz”的測試
bun test --test-name-pattern baz
完整文件可在 https://bun.nodejs.com.tw/docs/cli/test 找到