Bun

指南测试运行器

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

您可以结合使用 Bun 的测试运行器和 Happy DOM 来编写和运行浏览器测试。Happy DOM 实现了浏览器 API 的模拟版本,例如 documentlocation

要开始,请安装 happy-dom

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

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

happydom.ts
import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();

我们需要确保此文件在任何测试文件之前执行。这是 Bun 内置的 预加载 功能的作用。在项目根目录创建一个 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 后,此测试按预期运行。

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]

有关使用 Bun 编写浏览器测试的完整文档,请参阅 Happy DOM 仓库文档 > 测试运行器 > DOM