Skip to main content
You can use Testing Library with Bun’s test runner.
First, install Happy DOM (see Bun’s Happy DOM guide).
terminal
bun add -D @happy-dom/global-registrator

Next, install the Testing Library packages you plan to use, plus @testing-library/jest-dom for the matchers used later. For React:
terminal
bun add -D @testing-library/react @testing-library/dom @testing-library/jest-dom

Next, create preload scripts for Happy DOM and for Testing Library.
https://mintcdn.com/bun-1dd33a4e/JUhaF6Mf68z_zHyy/icons/typescript.svg?fit=max&auto=format&n=JUhaF6Mf68z_zHyy&q=85&s=7ac549adaea8d5487d8fbd58cc3ea35bhappydom.ts
import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();

For Testing Library, extend Bun’s expect function with Testing Library’s matchers. Optionally, run cleanup after each test to better match the behavior of test runners like Jest.
https://mintcdn.com/bun-1dd33a4e/JUhaF6Mf68z_zHyy/icons/typescript.svg?fit=max&auto=format&n=JUhaF6Mf68z_zHyy&q=85&s=7ac549adaea8d5487d8fbd58cc3ea35btesting-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();
});

Next, add these preload scripts to your bunfig.toml. You can also put everything in a single preload.ts script.
bunfig.toml
[test]
preload = ["./happydom.ts", "./testing-library.ts"]

If you use TypeScript, you also need declaration merging so the new matcher types show up in your editor. Create a type declaration file that extends Matchers.
https://mintcdn.com/bun-1dd33a4e/JUhaF6Mf68z_zHyy/icons/typescript.svg?fit=max&auto=format&n=JUhaF6Mf68z_zHyy&q=85&s=7ac549adaea8d5487d8fbd58cc3ea35bmatchers.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 {}
}

Now you can use Testing Library in your tests.
https://mintcdn.com/bun-1dd33a4e/JUhaF6Mf68z_zHyy/icons/typescript.svg?fit=max&auto=format&n=JUhaF6Mf68z_zHyy&q=85&s=7ac549adaea8d5487d8fbd58cc3ea35bmyComponent.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();
});

See the Testing Library docs, the Happy DOM repo, and DOM testing.