运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

DOM 测试

学习如何使用 Bun 搭配 happy-dom 和 React Testing Library 测试 DOM 元素和组件

Bun 的测试运行器可以很好地配合现有的组件和 DOM 测试库使用,包括 React Testing Library 和 happy-dom。

happy-dom

对于前端代码和组件的无头测试,我们推荐使用 happy-dom。它使用纯 JavaScript 实现了完整的 HTML 和 DOM API 集合,因此可以高度还原地模拟浏览器环境。

将 @happy-dom/global-registrator 软件包作为开发依赖项安装。

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

使用 Bun 的预加载功能,在测试运行前注册 happy-dom 全局变量,这样 document 等浏览器 API 就可以在全局作用域中使用。在项目根目录中创建名为 happydom.ts 的文件,并添加以下代码:

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

GlobalRegistrator.register();

要在执行 bun test 之前预加载此文件,请打开或创建 bunfig.toml 文件,并添加以下内容:

bunfig.toml
[test]
preload = ["./happydom.ts"]

bun test 现在会在测试之前执行 happydom.ts,因此测试可以使用 document 和 window 等浏览器 API。

dom.test.ts
import { test, expect } from "bun:test";

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

TypeScript 支持

根据你的 tsconfig.json 配置,你可能会在上面的代码中看到 "Cannot find name 'document'" 类型错误。要加载 document 和其他浏览器 API 的类型,请将以下三斜线指令添加到任意测试文件的顶部。

dom.test.ts
/// <reference lib="dom" />

import { test, expect } from "bun:test";

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

使用 bun test 运行测试:

terminal
bun test
Code
bun test v1.3.3

dom.test.ts:
✓ dom 测试 [0.82ms]

 1 pass
 0 fail
 1 expect() calls
Ran 1 test across 1 file. [125.00ms]

React 测试库

Bun 支持使用 React Testing Library 测试 React 组件。按照前文所述设置 happy-dom 后,正常安装并使用 React Testing Library。

terminal
bun add -d @testing-library/react @testing-library/jest-dom
component.test.tsx
/// <reference lib="dom" />

import { test, expect } from 'bun:test';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';

function Button({ children }: { children: React.ReactNode }) {
  return <button>{children}</button>;
}

test('渲染按钮', () => {
  render(<Button>点击我</Button>);
  expect(screen.getByRole('button')).toHaveTextContent('点击我');
});

高级 DOM 测试

自定义元素

使用相同的设置测试自定义元素和 Web 组件:

custom-element.test.ts
/// <reference lib="dom" />

import { test, expect } from "bun:test";

test("自定义元素", () => {
  // 定义一个自定义元素
  class MyElement extends HTMLElement {
    constructor() {
      super();
      this.innerHTML = "<p>自定义元素内容</p>";
    }
  }

  customElements.define("my-element", MyElement);

  // 在测试中使用它
  document.body.innerHTML = "<my-element></my-element>";
  const element = document.querySelector("my-element");
  expect(element?.innerHTML).toBe("<p>自定义元素内容</p>");
});

事件测试

测试 DOM 事件和用户交互:

events.test.ts
/// <reference lib="dom" />

import { test, expect } from "bun:test";

test("按钮点击事件", () => {
  let clicked = false;

  document.body.innerHTML = '<button id="test-btn">点击我</button>';
  const button = document.getElementById("test-btn");

  button?.addEventListener("click", () => {
    clicked = true;
  });

  button?.click();
  expect(clicked).toBe(true);
});

配置建议

全局设置

对于更复杂的设置,请创建一个同时注册全局模拟的预加载文件:

test-setup.ts
import { GlobalRegistrator } from "@happy-dom/global-registrator";
import "@testing-library/jest-dom";

// 注册 happy-dom 全局变量
GlobalRegistrator.register();

// 在此添加任何全局测试配置
global.ResizeObserver = class ResizeObserver {
  observe() {}
  unobserve() {}
  disconnect() {}
};

// 根据需要模拟其他 API
Object.defineProperty(window, "matchMedia", {
  writable: true,
  value: jest.fn().mockImplementation(query => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: jest.fn(),
    removeListener: jest.fn(),
    addEventListener: jest.fn(),
    removeEventListener: jest.fn(),
    dispatchEvent: jest.fn(),
  })),
});

然后更新你的 bunfig.toml:

bunfig.toml
[test]
preload = ["./test-setup.ts"]

故障排除

常见问题

DOM API 的 TypeScript 错误:在测试文件顶部包含 /// <reference lib="dom" /> 指令。

缺少全局变量:检查 preload 文件是否导入并注册了 @happy-dom/global-registrator。

React 组件渲染问题:检查是否已安装 @testing-library/react,并确认 happy-dom 已完成设置。

性能考虑

happy-dom 速度很快,但对于非常大型的测试套件,你可能需要:

  • 使用 beforeEach 在测试之间重置 DOM 状态
  • 避免在单个测试中创建过多 DOM 元素
  • 使用测试库提供的 cleanup 函数
test-setup.ts
import { afterEach } from "bun:test";
import { cleanup } from "@testing-library/react";

afterEach(() => {
  cleanup();
  document.body.innerHTML = "";
});