使用 Bun 和 happy-dom 编写浏览器 DOM 测试
使用 Happy DOM 和 Bun 的测试运行器编写浏览器测试。Happy DOM 实现了 document 和 location 等浏览器 API 的模拟版本。
安装 @happy-dom/global-registrator。
terminal
bun add -d @happy-dom/global-registrator
此模块导出了一个“注册器”,可将模拟的浏览器 API 注入全局作用域。
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 的测试。
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
Text
dom.test.ts:
✓ set button text [0.82ms]
1 pass
0 fail
1 expect() calls
Ran 1 test across 1 file. [125.00ms]
请参阅 Happy DOM 代码仓库 和 DOM 测试。