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

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

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

***

首先，安装 `happy-dom`。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun add -d @happy-dom/global-registrator
```

***

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

```ts happydom.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();
```

***

我们需要确保该文件在任何测试文件执行之前运行。这就需要使用 Bun 内置的 [*preload*]() 功能。在项目根目录下创建 `bunfig.toml` 文件（如果尚不存在），并添加以下内容。

`./happydom.ts` 文件应包含上述注册代码。

```toml bunfig.toml icon="settings" theme={"theme":{"light":"github-light","dark":"dracula"}}
[test]
preload = "./happydom.ts"
```

***

现在，在项目内运行 `bun test` 时会自动先执行 `happydom.ts`，我们就可以开始编写使用浏览器 API 的测试了。

```ts dom.test.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { test, expect } from "bun:test";

test("set button text", () => {
  document.body.innerHTML = `<button>My button</button>`;
  const button = document.querySelector("button");
  expect(button?.innerText).toEqual("My button");
});
```

***

Happy DOM 配置正确后，此测试将按预期运行。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun test
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}

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]
```

***

请参考 [Happy DOM 仓库](https://github.com/capricorn86/happy-dom) 以及 [文档 > 测试运行器 > DOM](/test/dom) 获取使用 Bun 编写浏览器测试的完整文档。
