執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

從 Jest 遷移到 Bun 的測試執行器

在許多情況下,Bun 的測試執行器可以在不修改程式碼的情況下執行 Jest 測試套件。使用 bun test 代替 npx jest 或 yarn test。

terminal
npx jest # [!code --]
yarn test # [!code --]
bun test # [!code ++]

你的測試檔案通常可以直接執行。

  • Bun 會在內部將從 @jest/globals 匯入的內容重寫為對應的 bun:test 內容。
  • 如果你相依 Jest 注入 test 和 expect 等全域性變數,Bun 也會執行相同的操作。

如果你更願意直接從 bun:test 匯入,請更新匯入語句。

test.ts
import { test, expect } from "@jest/globals"; // [!code --]
import { test, expect } from "bun:test"; // [!code ++]

從 Bun v1.2.19 開始,三斜線指令可以為全域性測試函式啟用 TypeScript 支援。將它新增到專案中的_一個檔案_,例如:

  • 專案根目錄下的 global.d.ts 檔案
  • 你的測試 preload.ts 設定檔案(如果在 bunfig.toml 中使用了 preload)
  • TypeScript 編譯時包含的任意一個 .ts 檔案
global.d.ts
/// <reference types="bun-types/test-globals" />

新增後,專案中的每個測試檔案都會獲得 Jest 全域性函式的 TypeScript 支援:

math.test.ts
describe("my test suite", () => {
  test("should work", () => {
    expect(1 + 1).toBe(2);
  });

  beforeAll(() => {
    // 設定程式碼
  });

  afterEach(() => {
    // 清理程式碼
  });
});

Bun 實現了 Jest 的大多數匹配器,但相容性並非 100%。請參閱編寫測試中的相容性表。


如果你使用 testEnvironment: "jsdom" 在類似瀏覽器的環境中執行測試,請按照 Bun 和 happy-dom 進行 DOM 測試指南,將瀏覽器 API 注入全域性作用域。該指南使用 happy-dom,這是 jsdom 的一個更輕量、更快速的替代方案。

bunfig.toml
[test]
preload = ["./happydom.ts"]

將 Jest 設定中的 bail 替換為 --bail 命令列引數。

terminal
bun test --bail=3

將 collectCoverage 替換為 --coverage 命令列引數。

terminal
bun test --coverage

將 testTimeout 替換為 --timeout CLI 標誌。

terminal
bun test --timeout 10000

許多其他 Jest 設定在 bun test 中並不適用。

  • transform — Bun 支援 TypeScript 和 JSX。使用外掛設定其他檔案型別。
  • extensionsToTreatAsEsm
  • haste — Bun 使用其自己的模組解析器
  • watchman、watchPlugins、watchPathIgnorePatterns — 使用 --watch 以監視模式執行測試
  • verbose — bun test 預設會報告每個測試。使用 --only-failures 或 --dots 以減少輸出(請參閱測試報告器)。

許多其他設定在 bunfig.toml 的 [test] 部分中都有對應項。例如:

  • setupFiles/setupFilesAfterEnv → preload
  • testPathIgnorePatterns → pathIgnorePatterns
  • rootDir → root
  • coverageDirectory → coverageDir
  • coverageReporters → coverageReporter
  • coverageThreshold → coverageThreshold(使用 0.9 這樣的分數,而非百分比)

請參閱測試設定。沒有對應項的設定不受支援。如果缺少你需要的功能,請提交功能請求。


另見: