Skip to content

Bun 的测试运行器与现有的组件和 DOM 测试库(包括 React Testing Library 和 happy-dom)配合良好。

happy-dom

对于为前端代码和组件编写无头测试,我们推荐 happy-dom。Happy DOM 在纯 JavaScript 中实现了一整套 HTML 和 DOM API,使其能够以高保真度模拟浏览器环境。

要开始使用,请将 @happy-dom/global-registrator 包作为开发依赖安装。

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

我们将使用 Bun 的预加载功能在运行测试之前注册 happy-dom 全局变量。此步骤将使 document 等浏览器 API 在全局范围内可用。在项目根目录中创建一个名为 happydom.ts 的文件,并添加以下代码:

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

GlobalRegistrator.register();

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

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

这将在你运行 bun test 时执行 happydom.ts。现在你可以编写使用 documentwindow 等浏览器 API 的测试。

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 "注入" 类型,请在任何测试文件的顶部添加以下三斜杠指令。

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 运行此测试:

bash
bun test
bun test v1.3.3

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

 1 pass
 0 fail
 1 expect() calls
Ran 1 tests across 1 files. 1 total [125.00ms]

React Testing Library

Bun 与 React Testing Library 无缝配合以测试 React 组件。按照上述设置 happy-dom 后,你可以正常安装和使用 React Testing Library。

bash
bun add -d @testing-library/react @testing-library/jest-dom
ts
/// <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('renders button', () => {
  render(<Button>Click me</Button>);
  expect(screen.getByRole('button')).toHaveTextContent('Click me');
});

高级 DOM 测试

自定义元素

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

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

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

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

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

  // 在测试中使用它
  document.body.innerHTML = "<my-element></my-element>";
  const element = document.querySelector("my-element");
  expect(element?.innerHTML).toBe("<p>Custom element content</p>");
});

事件测试

测试 DOM 事件和用户交互:

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

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

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

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

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

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

配置提示

全局设置

对于更复杂的 DOM 测试设置,你可以创建更全面的预加载文件:

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

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

故障排除

常见问题

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

缺少全局变量:确保在你的预加载文件中正确导入和注册了 @happy-dom/global-registrator

React 组件渲染问题:确保你已安装 @testing-library/react 并正确设置了 happy-dom。

性能考虑

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

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

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

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