Skip to content

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


作為使用 Testing Library 的先決條件,你需要安裝 Happy Dom。(更多信息請參閱 Bun 的 Happy DOM 指南)。

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

接下來,你應該安裝你計劃使用的 Testing Library 包。例如,如果你正在為 React 設置測試,你的安裝可能如下所示。你還需要安裝 @testing-library/jest-dom 以使匹配器工作。

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

接下來,你需要為 Happy DOM 和 Testing Library 創建一個 preload 腳本。有關 Happy DOM 設置腳本的更多詳細信息,請參閱 Bun 的 Happy DOM 指南

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

GlobalRegistrator.register();

對於 Testing Library,你應該使用 Testing Library 的匹配器擴展 Bun 的 expect 函數。可選地,為了更好地匹配 Jest 等測試運行器的行為,你可能希望在每個測試後運行清理。

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();
});

接下來,將這些 preload 腳本添加到你的 bunfig.toml(如果你願意,也可以將所有內容放在一個 preload.ts 腳本中)。

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

如果你使用 TypeScript,你還需要使用聲明合並來使新的匹配器類型出現在你的編輯器中。為此,創建一個類型聲明文件來擴展 Matchers,如下所示。

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, T> {}
  interface AsymmetricMatchers extends TestingLibraryMatchers {}
}

你現在應該能夠在測試中使用 Testing Library

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

test("可以使用 Testing Library", () => {
  render(MyComponent);
  const myComponent = screen.getByTestId("my-component");
  expect(myComponent).toBeInTheDocument();
});

請參閱 Testing Library 文檔Happy DOM 倉庫文檔 > 測試運行器 > DOM 獲取使用 Bun 編寫瀏覽器測試的完整文檔。

Bun學習網由www.bunjs.com.cn整理維護