Skip to content

你可以使用 Bun 的测试运行器与 Happy DOM 一起编写和运行浏览器测试。Happy DOM 实现了浏览器 API(如 documentlocation)的模拟版本。


首先,安装 happy-dom

sh
bun add -d @happy-dom/global-registrator

该模块导出一个 "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 test
txt

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 仓库文档 > 测试运行器 > DOM 获取使用 Bun 编写浏览器测试的完整文档。

Bun学习网由www.bunjs.com.cn整理维护