Skip to content

你可以在 Bun 的测试运行器中使用 Testing Library


作为使用 Testing Library 的先决条件,你需要安装 Happy Dom。(更多信息请参阅 Bun 的 Happy DOM 指南)。

sh
bun add -D @happy-dom/global-registrator

接下来,你应该安装你计划使用的 Testing Library 包。例如,如果你正在为 React 设置测试,你的安装可能如下所示。你还需要安装 @testing-library/jest-dom 以使匹配器工作。

sh
bun add -D @testing-library/react @testing-library/dom @testing-library/jest-dom

接下来,你需要为 Happy DOM 和 Testing Library 创建一个 preload 脚本。有关 Happy DOM 设置脚本的更多详细信息,请参阅 Bun 的 Happy DOM 指南

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

GlobalRegistrator.register();

对于 Testing Library,你应该使用 Testing Library 的匹配器扩展 Bun 的 expect 函数。可选地,为了更好地匹配 Jest 等测试运行器的行为,你可能希望在每个测试后运行清理。

ts
import { afterEach, expect } from "bun:test";
import { cleanup } from "@testing-library/react";
import * as matchers from "@testing-library/jest-dom/matchers";

expect.extend(matchers);

// 可选:在每个测试后清理 `render`
afterEach(() => {
  cleanup();
});

接下来,将这些 preload 脚本添加到你的 bunfig.toml(如果你愿意,也可以将所有内容放在一个 preload.ts 脚本中)。

toml
[test]
preload = ["./happydom.ts", "./testing-library.ts"]

如果你使用 TypeScript,你还需要使用声明合并来使新的匹配器类型出现在你的编辑器中。为此,创建一个类型声明文件来扩展 Matchers,如下所示。

ts
import { TestingLibraryMatchers } from "@testing-library/jest-dom/matchers";
import { Matchers, AsymmetricMatchers } from "bun:test";

declare module "bun:test" {
  interface Matchers<T> extends TestingLibraryMatchers<typeof expect.stringContaining, T> {}
  interface AsymmetricMatchers extends TestingLibraryMatchers {}
}

你现在应该能够在测试中使用 Testing Library

tsx
import { test, expect } from "bun:test";
import { screen, render } from "@testing-library/react";
import { MyComponent } from "./myComponent";

test("可以使用 Testing Library", () => {
  render(MyComponent);
  const myComponent = screen.getByTestId("my-component");
  expect(myComponent).toBeInTheDocument();
});

请参阅 Testing Library 文档Happy DOM 仓库文档 > 测试运行器 > DOM 获取使用 Bun 编写浏览器测试的完整文档。

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