Bun のテストランナーで Testing Library を使用できます。
Testing Library を使用するための前提条件として、Happy Dom をインストールする必要があります。(詳細は Bun の Happy DOM ガイド を参照してください。)
bun add -D @happy-dom/global-registrator次に、使用する Testing Library パッケージをインストールします。たとえば、React のテストを設定する場合は、次のようになります。また、後でマッチャーを機能させるために @testing-library/jest-dom もインストールする必要があります。
bun add -D @testing-library/react @testing-library/dom @testing-library/jest-dom次に、Happy DOM と Testing Library のプリロードスクリプトを作成する必要があります。Happy DOM のセットアップスクリプトの詳細については、Bun の Happy DOM ガイド を参照してください。
import { GlobalRegistrator } from "@happy-dom/global-registrator";
GlobalRegistrator.register();Testing Library では、Testing Library のマッチャーを使用して Bun の expect 関数を拡張する必要があります。オプションですが、Jest のようなテストランナーの動作により良く合わせるために、各テスト後にクリーンアップを実行することもできます。
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 に追加します(必要に応じて、単一の preload.ts スクリプトにすべてを含めることもできます)。
[test]
preload = ["./happydom.ts", "./testing-library.ts"]TypeScript を使用している場合、新しいマッチャーの型をエディターに表示させるために、宣言マージを使用する必要があります。これを行うには、次のように Matchers を拡張する型宣言ファイルを作成します。
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 を使用できるようになります。
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();
});Bun でブラウザテストを記述する完全なドキュメントについては、Testing Library ドキュメント、Happy DOM リポジトリ、および ドキュメント > テストランナー > DOM を参照してください。