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

在 Bun 中使用 Testing Library

你可以在 Bun 的測試執行器中使用 Testing Library。


首先,安裝 Happy DOM(請參閱 Bun 的 Happy DOM 指南)。

terminal
bun add -D @happy-dom/global-registrator

接下來,安裝你計劃使用的 Testing Library 軟體包,以及用於後文匹配器的 @testing-library/jest-dom。對於 React:

terminal
bun add -D @testing-library/react @testing-library/dom @testing-library/jest-dom

接下來,為 Happy DOM 和 Testing Library 建立預載入指令碼。

happydom.ts
import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();

對於 Testing Library,使用其匹配器擴充套件 Bun 的 expect 函式。你還可以選擇在每個測試後執行清理,以更好地匹配 Jest 等測試執行器的行為。

testing-library.ts
import { afterEach, expect } from "bun:test";
import { cleanup } from "@testing-library/react";
import * as matchers from "@testing-library/jest-dom/matchers";

expect.extend(matchers);

// 可選:在每個測試後清理 `render`
afterEach(() => {
  cleanup();
});

接下來,將這些預載入指令碼新增到你的 bunfig.toml 中。如果將它們合併到單個預載入指令碼中,請在 GlobalRegistrator.register() 之後使用 await import() 載入 @testing-library/* 軟體包。Bun 會在 register() 執行之前執行靜態 import,此時 screen 查詢會丟擲異常。

bunfig.toml
[test]
preload = ["./happydom.ts", "./testing-library.ts"]

如果你使用 TypeScript,還需要進行宣告合併,以便新的匹配器型別顯示在編輯器中。建立一個擴充套件 Matchers 的型別宣告檔案。

matchers.d.ts
import { TestingLibraryMatchers } from "@testing-library/jest-dom/matchers";
import { Matchers, AsymmetricMatchers } from "bun:test";

declare module "bun:test" {
  interface Matchers<T> extends TestingLibraryMatchers<typeof expect.stringContaining, void> {}
  interface AsymmetricMatchers extends TestingLibraryMatchers<any, any> {}
}

現在,你可以在測試中使用 Testing Library。

myComponent.test.tsx
import { test, expect } from "bun:test";
import { screen, render } from "@testing-library/react";
import { MyComponent } from "./myComponent";

test("Can use Testing Library", () => {
  render(<MyComponent />);
  const myComponent = screen.getByTestId("my-component");
  expect(myComponent).toBeInTheDocument();
});

請參閱 Testing Library 文件、Happy DOM 儲存庫以及 DOM 測試。