> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 Bun 和 happy-dom 编写浏览器 DOM 测试

使用 [Happy DOM](https://github.com/capricorn86/happy-dom) 配合 Bun 的测试运行器编写浏览器测试。Happy DOM 实现了浏览器 API（如 `document` 和 `location`）的模拟版本。

***

安装 `@happy-dom/global-registrator`。

```sh terminal icon="terminal" theme={null}
bun add -d @happy-dom/global-registrator
```

***

该模块导出了一个"注册器"，它将模拟的浏览器 API 注入到全局作用域中。

```ts happydom.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();
```

***

此文件需要在任何测试文件之前运行。这正是 Bun 内置的 [*preload*]() 选项的工作。在项目根目录创建 `bunfig.toml` 文件（如果尚不存在）并添加以下行。

`./happydom.ts` 文件应包含上一步中的注册代码。

```toml bunfig.toml icon="settings" theme={null}
[test]
preload = "./happydom.ts"
```

***

现在 `bun test` 会在测试文件之前执行 `happydom.ts`，这样你就可以编写使用浏览器 API 的测试了。

```ts dom.test.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { test, expect } from "bun:test";

test("设置按钮文本", () => {
  document.body.innerHTML = `<button>我的按钮</button>`;
  const button = document.querySelector("button");
  expect(button?.innerText).toEqual("我的按钮");
});
```

***

注册了 Happy DOM 后，测试通过。

```sh terminal icon="terminal" theme={null}
bun test
```

```txt theme={null}

dom.test.ts:
✓ 设置按钮文本 [0.82ms]

 1 通过
 0 失败
 1 个 expect() 调用
跨 1 个文件运行了 1 个测试。 [125.00ms]
```

***

参见 [Happy DOM 仓库](https://github.com/capricorn86/happy-dom) 和 [DOM 测试](/test/dom)。
