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 writing headless tests for your frontend code and components, we recommend happy-dom. Happy DOM implements a complete set of HTML and DOM APIs in plain JavaScript, making it possible to simulate a browser environment with high fidelity. To get started install the @happy-dom/global-registrator package as a dev dependency.
terminal
We’ll be using Bun’s preload functionality to register the happy-dom globals before running our tests. This step will make browser APIs like document available in the global scope. Create a file called happydom.ts in the root of your project and add 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
This will execute happydom.ts when you run bun test. Now you can write tests that 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 code above. To “inject” the types for document and other browser APIs, add the following triple-slash directive to the top of any test file.
dom.test.ts
Let’s run this test with bun test:
terminal

React Testing Library

Bun works seamlessly with React Testing Library for testing React components. After setting up happy-dom as shown above, you can install and use React Testing Library normally.
terminal
component.test.tsx

Advanced DOM Testing

Custom Elements

You can test custom elements and web components using the same setup:
custom-element.test.ts

Event Testing

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

Configuration Tips

Global Setup

For more complex DOM testing setups, you can create a more comprehensive preload file:
test-setup.ts
Then update your bunfig.toml:
bunfig.toml

Troubleshooting

Common Issues

TypeScript errors for DOM APIs: Make sure to include the /// <reference lib="dom" /> directive at the top of your test files. Missing globals: Ensure that @happy-dom/global-registrator is properly imported and registered in your preload file. React component rendering issues: Make sure you’ve installed both @testing-library/react and have happy-dom set up correctly.

Performance Considerations

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