Bun のテストランナーと Happy DOM を組み合わせてブラウザテストを記述・実行できます。Happy DOM は document や location などのブラウザ API のモックバージョンを実装します。
始めるには、happy-dom をインストールします。
sh
bun add -d @happy-dom/global-registratorこのモジュールはモックされたブラウザ API をグローバルスコープに注入する「レジストラー」をエクスポートします。
ts
import { GlobalRegistrator } from "@happy-dom/global-registrator";
GlobalRegistrator.register();このファイルがテストファイルの前に実行されるようにする必要があります。これは Bun の組み込み preload 機能で行います。プロジェクトのルートに bunfig.toml ファイルを作成し(まだ存在しない場合)、以下の行を追加します。
./happydom.ts ファイルには上記の登録コードを含める必要があります。
toml
[test]
preload = "./happydom.ts"これで、プロジェクト内で bun test を実行すると、自動的に最初に happydom.ts が実行されます。ブラウザ API を使用するテストを記述し始められます。
ts
import { test, expect } from "bun:test";
test("ボタンテキストを設定", () => {
document.body.innerHTML = `<button>My button</button>`;
const button = document.querySelector("button");
expect(button?.innerText).toEqual("My button");
});Happy DOM が正しく設定されると、このテストは期待通りに実行されます。
sh
bun testtxt
dom.test.ts:
✓ set button text [0.82ms]
1 pass
0 fail
1 expect() calls
Ran 1 tests across 1 files. 1 total [125.00ms]Bun でブラウザテストを記述する完全なドキュメントについては、Happy DOM リポジトリ と ドキュメント > テストランナー > DOM を参照してください。