Bun’s test runner is compatible with popular DOM and component testing libraries. The recommended setup uses happy-dom to simulate a browser environment.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/oven-sh/bun/llms.txt
Use this file to discover all available pages before exploring further.
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.Create a preload file
Create
happydom.ts at the root of your project to register the browser globals:happydom.ts
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
TypeScript errors for document or window
TypeScript errors for document or window
Add the triple-slash DOM reference to the top of the file:Alternatively, add
"lib": ["dom"] to your tsconfig.json.Globals not available in tests
Globals not available in tests
Ensure your preload file is registered in
bunfig.toml and that GlobalRegistrator.register() is called before any tests run.React component rendering issues
React component rendering issues
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.State leaking between tests
State leaking between tests
Reset the DOM in
afterEach to prevent state from one test affecting the next: