Skip to main content
Bun’s test runner plays well with existing component and DOM testing libraries, including React Testing Library and happy-dom.

happy-dom

For headless tests of your frontend code and components, we recommend happy-dom. It implements a complete set of HTML and DOM APIs in plain JavaScript, so it can simulate a browser environment with high fidelity. Install the @happy-dom/global-registrator package as a dev dependency.
terminal
Use Bun’s preload feature to register the happy-dom globals before your tests run, which makes browser APIs like document available in the global scope. Create a file called happydom.ts in the root of your project with the following code:
happydom.ts
To preload this file before bun test, open or create a bunfig.toml file and add the following lines.
bunfig.toml
bun test now executes happydom.ts before your tests, so they can use browser APIs like document and window.
dom.test.ts

TypeScript Support

Depending on your tsconfig.json setup, you may see a “Cannot find name ‘document’” type error in the earlier code. To load the types for document and other browser APIs, add the following triple-slash directive to the top of any test file.
dom.test.ts
Run the test with bun test:
terminal

React Testing Library

Bun works with React Testing Library for testing React components. After setting up happy-dom as described earlier, install and use React Testing Library normally.
terminal
component.test.tsx

Advanced DOM Testing

Custom Elements

Test custom elements and web components with the same setup:
custom-element.test.ts

Event Testing

Test DOM events and user interactions:
events.test.ts

Configuration Tips

Global Setup

For more involved setups, create a preload file that also registers global mocks:
test-setup.ts
Then update your bunfig.toml:
bunfig.toml

Troubleshooting

Common Issues

TypeScript errors for DOM APIs: Include the /// <reference lib="dom" /> directive at the top of your test files. Missing globals: Check that your preload file imports and registers @happy-dom/global-registrator. React component rendering issues: Check that @testing-library/react is installed and happy-dom is set up.

Performance Considerations

happy-dom is fast, but for very large test suites you may want to:
  • Use beforeEach to reset the DOM state between tests
  • Avoid creating too many DOM elements in a single test
  • Use cleanup functions from testing libraries
test-setup.ts