English

Bunのbun testとhappy-domで、DOMを使うテストを書く方法

​​Bun​happy-dom,TypeScript,テスト

bun test で document を使うテストを動かすと、そのままでは ReferenceError: document is not defined で失敗します。happy-dom を入れて、テストの前に読み込むファイル(preload)で登録すると、document や window が使えるようになり、テストが通ります。

ボタンのクリックやフォームの送信で画面の一部が書き換わる処理を、ブラウザーを起動せずに単体テストしたいときの方法です。設定の手順に加えて、テストの間で DOM が残る問題、TypeScript の型エラー、preload にかかる時間を、検証環境で実際に動かした出力でまとめました。

補足

検証環境は Ubuntu 24.04(x86_64)、Bun 1.4.4、happy-dom 21.0.4(@happy-dom/global-registrator 21.0.4)、TypeScript 7.0.2 です。React などの UI ライブラリのコンポーネントのテスト、jsdom との比較、Windows と macOS は試していません。出力に出る検証環境のパスは /path/to/todo-app/ に置き換えています。

テストする関数と、準備なしで動かしたときのエラー

例として、やることリストの部品を作る関数 mountTodo を todo.ts に用意しました。渡された要素の中にフォームとリストを作り、送信されたら入力の文字をリストに1行足して、件数の表示を変えます。

ts
// やることリストの部品。root の中に入力欄・ボタン・リスト・件数を作る
export function mountTodo(root: HTMLElement): void {
  root.innerHTML = `
    <form>
      <input name="title" aria-label="やること" />
      <button type="submit">追加</button>
    </form>
    <ul></ul>
    <p class="count">0件</p>
  `;
  const form = root.querySelector("form")!;
  const input = root.querySelector("input")!;
  const list = root.querySelector("ul")!;
  const count = root.querySelector(".count")!;

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    const title = input.value.trim();
    if (title === "") return;
    const li = document.createElement("li");
    li.textContent = title;
    list.append(li);
    input.value = "";
    count.textContent = `${list.children.length}件`;
  });
}

テストファイル todo.test.ts では、document.body に土台の div を置いて mountTodo を呼び、入力欄に文字を入れてボタンの click() を呼びます。そのあとで、リストの中身と件数の表示を確かめます。

ts
import { expect, test } from "bun:test";
import { mountTodo } from "./todo";

test("入力して追加すると、リストに1行増える", () => {
  document.body.innerHTML = `<div id="app"></div>`;
  mountTodo(document.querySelector<HTMLElement>("#app")!);

  const input = document.querySelector("input")!;
  input.value = "牛乳を買う";
  document.querySelector("button")!.click();

  const items = [...document.querySelectorAll("li")].map((li) => li.textContent);
  expect(items).toEqual(["牛乳を買う"]);
  expect(document.querySelector(".count")!.textContent).toBe("1件");
  expect(input.value).toBe("");
});

test("空白だけのときは追加しない", () => {
  document.body.innerHTML = `<div id="app"></div>`;
  mountTodo(document.querySelector<HTMLElement>("#app")!);

  document.querySelector("input")!.value = "   ";
  document.querySelector("button")!.click();

  expect(document.querySelectorAll("li").length).toBe(0);
  expect(document.querySelector(".count")!.textContent).toBe("0件");
});

この2つのファイルだけのフォルダで bun test を実行すると、2件とも失敗します。Bun はブラウザーではないので、document がありません。

text
$ bun test
bun test v1.4.4 (38afee6c8)

todo.test.ts:
1 | import { expect, test } from "bun:test";
2 | import { mountTodo } from "./todo";
3 | 
4 | test("入力して追加すると、リストに1行増える", () => {
5 |   document.body.innerHTML = `<div id="app"></div>`;
      ^
ReferenceError: document is not defined
      at <anonymous> (/path/to/todo-app/todo.test.ts:5:3)
(fail) 入力して追加すると、リストに1行増える [0.35ms]
(2件目も同じエラーなので略)

 0 pass
 2 fail
Ran 2 tests across 1 file. [4.00ms]

happy-dom を入れて、preload で登録する

Bun の公式ドキュメントにある DOM を使うテストの説明では、happy-dom を勧めています。手順は3つです。

まず、@happy-dom/global-registrator を開発用の依存として入れます。happy-dom 本体も一緒に入りました。

text
$ bun add -d @happy-dom/global-registrator
bun add v1.4.4 (38afee6c8)
Saved lockfile

installed @happy-dom/global-registrator@21.0.4

10 packages installed [23.00ms]
$ bun pm ls --all | grep happy-dom
├── @happy-dom/global-registrator@21.0.4
├── happy-dom@21.0.4

次に、プロジェクトの一番上に happydom.ts を作ります。GlobalRegistrator.register() を呼ぶと、happy-dom の document や window がグローバルに置かれます。

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

GlobalRegistrator.register();

最後に、bunfig.toml の [test] に preload を書きます。bun test は、テストファイルより先にこのファイルを実行します。

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

もう一度 bun test を実行すると、2件とも通りました。click() でフォームの送信が起き、submit イベントの処理でリストと件数が書き換わっています。

text
$ bun test
bun test v1.4.4 (38afee6c8)

todo.test.ts:
(pass) 入力して追加すると、リストに1行増える [11.96ms]
(pass) 空白だけのときは追加しない [4.51ms]

 2 pass
 0 fail
 5 expect() calls
Ran 2 tests across 1 file. [142.00ms]

bunfig.toml を書かずに、実行のたびに bun test --preload ./happydom.ts と指定する方法もあります。テストの設定についての公式ドキュメントでは、この2つは同じ意味だと説明されています。

前のテストで足した要素が、次のテストに残る

happy-dom の document は、1回の bun test の間ずっと同じものが使われます。テストが変えた DOM は、元に戻りません。

次の leak.test.ts のテストは、どちらも body に p を1つ足して、p が1つだけあることを確かめます。1つずつなら通る内容です。

ts
import { expect, test } from "bun:test";

test("1つ目:body に p を1つ足す", () => {
  document.body.append(document.createElement("p"));
  expect(document.querySelectorAll("p").length).toBe(1);
});

test("2つ目:body に p を1つ足す", () => {
  document.body.append(document.createElement("p"));
  expect(document.querySelectorAll("p").length).toBe(1);
});

別のファイル other.test.ts には、body が空であることを確かめるテストを置きました。

ts
import { expect, test } from "bun:test";

test("別のファイルのテストから body を見る", () => {
  console.log("body の中身:", document.body.innerHTML);
  expect(document.body.children.length).toBe(0);
});

2つのファイルをまとめて実行すると、2つ目のテストは p が2つになって失敗しました。別のファイルのテストにも、前のファイルで足した p が2つ残っています。

text
$ bun test leak.test.ts other.test.ts
bun test v1.4.4 (38afee6c8)

leak.test.ts:
(pass) 1つ目:body に p を1つ足す [1.05ms]
(コードの抜き出しは略)
error: expect(received).toBe(expected)

Expected: 1
Received: 2

      at <anonymous> (/path/to/todo-app/leak.test.ts:10:49)
(fail) 2つ目:body に p を1つ足す [0.35ms]

other.test.ts:
body の中身: <p></p><p></p>
(コードの抜き出しは略)
error: expect(received).toBe(expected)

Expected: 0
Received: 2

      at <anonymous> (/path/to/todo-app/other.test.ts:5:41)
(fail) 別のファイルのテストから body を見る [0.53ms]

 1 pass
 2 fail
 3 expect() calls
Ran 3 tests across 2 files. [127.00ms]

todo.test.ts が通っていたのは、どのテストも初めに document.body.innerHTML を書き換えていたからです。そうしていないテストは、leak.test.ts のように、1つだけなら通るのに、ほかのテストと一緒に動かすと失敗します。

preload で afterEach を登録して、毎回 body を空にする

happydom.ts に afterEach を足して、テストが1つ終わるたびに body の中を空にしました。テストのライフサイクル(フック)についての公式ドキュメントでは、preload のファイルに書いたフックは、複数のファイルをまとめて実行するとき、全体に適用されると説明されています。

ts
import { afterEach } from "bun:test";
import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();

// テストが1つ終わるたびに、body の中を空にする
afterEach(() => {
  document.body.innerHTML = "";
});

同じ2つのファイルを実行すると、3件とも通り、別のファイルから見た body も空になりました。

text
$ bun test leak.test.ts other.test.ts
bun test v1.4.4 (38afee6c8)

leak.test.ts:
(pass) 1つ目:body に p を1つ足す [2.24ms]
(pass) 2つ目:body に p を1つ足す [0.26ms]

other.test.ts:
body の中身: 
(pass) 別のファイルのテストから body を見る [0.43ms]

 3 pass
 0 fail
 3 expect() calls
Ran 3 tests across 2 files. [146.00ms]
ポイント

afterEach を preload のファイルに書いておけば、テストファイルごとに後片付けを書かなくても、すべてのテストの後に body が空になります。

要素の幅は 0 のまま

happy-dom の上では、getBoundingClientRect() や offsetWidth のように、レイアウトで決まる幅の値が 0 になりました。幅 120px の div を置いて、いくつかの値を出したテスト layout.test.ts です。

ts
import { expect, test } from "bun:test";

test("happy-dom はレイアウトを計算しない", () => {
  document.body.innerHTML = `<div style="width: 120px; height: 40px">箱</div>`;
  const box = document.querySelector("div")!;

  console.log("getComputedStyle の width:", getComputedStyle(box).width);
  console.log("getBoundingClientRect の width:", box.getBoundingClientRect().width);
  console.log("offsetWidth:", box.offsetWidth);
  console.log("window.innerWidth:", window.innerWidth);

  expect(getComputedStyle(box).width).toBe("120px");
  expect(box.getBoundingClientRect().width).toBe(0);
});
text
$ bun test layout.test.ts
bun test v1.4.4 (38afee6c8)

layout.test.ts:
getComputedStyle の width: 120px
getBoundingClientRect の width: 0
offsetWidth: 0
window.innerWidth: 1024
(pass) happy-dom はレイアウトを計算しない [5.07ms]

 1 pass
 0 fail
 2 expect() calls
Ran 1 test across 1 file. [99.00ms]

getComputedStyle は、style に書いた 120px を返しました。一方、getBoundingClientRect() と offsetWidth は 0 です。要素の実際の幅で表示を変える処理(はみ出したら「もっと見る」を出す、など)は、この値を頼りにテストできません。

window.innerWidth は 1024 でした。global-registrator の README には、GlobalRegistrator.register({ url: 'http://localhost:3000', width: 1920, height: 1080 }) のように、url、width、height を渡す例が載っています。

TypeScript の型チェックで document が見つからないとき

bun test は型をチェックしないので、ここまでのテストは型の設定に関係なく動きます。ただ、tsc で型をチェックすると、tsconfig.json の lib に DOM が入っていない場合はエラーになります。lib を ["ESNext"] だけにして試したところ、31件のエラーが出ました。

text
$ bun x tsc
happydom.ts(8,3): error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.
(略)
todo.ts(2,33): error TS2304: Cannot find name 'HTMLElement'.
todo.ts(16,36): error TS7006: Parameter 'event' implicitly has an 'any' type.
todo.ts(20,16): error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.

直し方は2つあります。1つは、tsconfig.json の lib に "DOM" を足すことです。tsconfig.json の1か所を変えるだけで、この記事の todo.ts のようなブラウザー向けのコードも、テストファイルも、まとめてチェックが通ります。

json
"lib": ["ESNext", "DOM"],

もう1つは、ファイルの先頭に /// <reference lib="dom" /> を書くことです。Bun の公式ドキュメントでは、テストファイルの先頭に書く方法が紹介されています。今回は lib を ["ESNext"] のままにして、テストファイルでない todo.ts と happydom.ts も含め、DOM を使う6つのファイルすべての先頭にこの1行を足しました。これでエラーはなくなりました。どちらの直し方でも、bun x tsc は何も出さずに終わっています。

ts
/// <reference lib="dom" />
import { expect, test } from "bun:test";
import { mountTodo } from "./todo";

preload にかかる時間

bunfig.toml の preload は、DOM を使わないテストを実行するときにも読み込まれます。DOM を使わないテスト1件だけのファイルで、bun test を10回ずつ実行し、最後に出る Ran の行の時間を比べました。

preload あり(平均 93.8ms)と preload なし(平均 2.0ms)の時間を比べた棒グラフ
DOM を使わないテスト1件を10回ずつ実行したときの、Ran の行の時間の平均

happy-dom を preload したときは 87ms〜107ms(平均 93.8ms)、bunfig.toml を外したときは10回とも 2ms でした。テストそのものは同じなので、preload の分だけ 90ms ほど増えています。

この時間は、テストファイルの数に比例しては増えませんでした。5つのファイルの7件をまとめて実行したときの Ran は 98ms です。

text
$ bun test
(各テストの行は略)

 7 pass
 0 fail
 11 expect() calls
Ran 7 tests across 5 files. [98.00ms]

​Posted by 86