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

在 Bun 中使用 Testing Library

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


首先,安装 Happy DOM(请参阅 Bun 的 Happy DOM 指南)。

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

接下来,安装你计划使用的 Testing Library 软件包,以及用于后文匹配器的 @testing-library/jest-dom。对于 React:

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

接下来,为 Happy DOM 和 Testing Library 创建预加载脚本。

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

GlobalRegistrator.register();

对于 Testing Library,使用其匹配器扩展 Bun 的 expect 函数。你还可以选择在每个测试后运行清理,以更好地匹配 Jest 等测试运行器的行为。

testing-library.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();
});

接下来,将这些预加载脚本添加到你的 bunfig.toml 中。如果将它们合并到单个预加载脚本中,请在 GlobalRegistrator.register() 之后使用 await import() 加载 @testing-library/* 软件包。Bun 会在 register() 运行之前执行静态 import,此时 screen 查询会抛出异常。

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

如果你使用 TypeScript,还需要进行声明合并,以便新的匹配器类型显示在编辑器中。创建一个扩展 Matchers 的类型声明文件。

matchers.d.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, void> {}
  interface AsymmetricMatchers extends TestingLibraryMatchers<any, any> {}
}

现在,你可以在测试中使用 Testing Library。

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

test("Can use Testing Library", () => {
  render(<MyComponent />);
  const myComponent = screen.getByTestId("my-component");
  expect(myComponent).toBeInTheDocument();
});

请参阅 Testing Library 文档、Happy DOM 仓库以及 DOM 测试。