Bun

DOM 测试

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

happy-dom

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

首先,将 @happy-dom/global-registrator 包作为开发依赖安装。

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

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

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

GlobalRegistrator.register();

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

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

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

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

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

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

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

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

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

让我们用 bun test 运行这个测试

bun test
bun test v1.3.0

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

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