Skip to main content
Bun’s test runner is compatible with popular DOM and component testing libraries. The recommended setup uses happy-dom to simulate a browser environment.

Setting up happy-dom

happy-dom implements a complete set of HTML and DOM APIs in JavaScript, making it possible to run browser-targeting code in Bun without a real browser.
1

Install the package

2

Create a preload file

Create happydom.ts at the root of your project to register the browser globals:
happydom.ts
3

Register the preload in bunfig.toml

bunfig.toml
This executes happydom.ts before any test file runs, making document, window, and other browser globals available.

Writing DOM tests

Once happy-dom is registered, you can use browser APIs directly in your tests:
dom.test.ts
Add /// <reference lib="dom" /> at the top of test files to get TypeScript type checking for browser APIs like document and window.

React Testing Library

After setting up happy-dom, install React Testing Library:
Button.test.tsx

Testing custom elements

happy-dom supports the Custom Elements API:
custom-element.test.ts

Advanced setup

For projects that need additional globals polyfilled (e.g., ResizeObserver, matchMedia), create a more comprehensive preload file:
test-setup.ts
bunfig.toml

JSDOM as an alternative

If you prefer jsdom, install it and register it similarly:
jsdom-setup.ts
bunfig.toml

Troubleshooting

Add the triple-slash DOM reference to the top of the file:
Alternatively, add "lib": ["dom"] to your tsconfig.json.
Ensure your preload file is registered in bunfig.toml and that GlobalRegistrator.register() is called before any tests run.
Confirm that both @testing-library/react and @happy-dom/global-registrator are installed as dev dependencies, and that the preload file is loaded before test files.
Reset the DOM in afterEach to prevent state from one test affecting the next: