Skip to main content
你可以使用 Bun 的测试运行器结合 Happy DOM 来编写和运行浏览器测试。Happy DOM 实现了浏览器 API(如 documentlocation)的模拟版本。
首先,安装 happy-dom
terminal
bun add -d @happy-dom/global-registrator

该模块导出一个“注册器”,将模拟的浏览器 API 注入到全局作用域。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79happydom.ts
import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();

我们需要确保该文件在任何测试文件执行之前运行。这就需要使用 Bun 内置的 preload 功能。在项目根目录下创建 bunfig.toml 文件(如果尚不存在),并添加以下内容。 ./happydom.ts 文件应包含上述注册代码。
bunfig.toml
[test]
preload = "./happydom.ts"

现在,在项目内运行 bun test 时会自动先执行 happydom.ts,我们就可以开始编写使用浏览器 API 的测试了。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79dom.test.ts
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 配置正确后,此测试将按预期运行。
terminal
bun test

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 编写浏览器测试的完整文档。