Bun

指南测试运行器

将 Testing Library 与 Bun 一起使用

您可以使用 Testing Library 和 Bun 的测试运行器。

在使用 Testing Library 之前,您需要安装 Happy Dom。 (有关更多信息,请参阅 Bun 的 Happy DOM 指南)。

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

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

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

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

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

GlobalRegistrator.register();

对于 Testing Library,您将希望使用 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);

// Optional: cleans up `render` after each test
afterEach(() => {
  cleanup();
});

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

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, T> {}
  interface AsymmetricMatchers extends TestingLibraryMatchers {}
}

您现在应该可以在您的测试中使用 Testing Library 了

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

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