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
document available in the global scope. Create a file called happydom.ts in the root of your project and add the following code:
bun test, open or create a bunfig.toml file and add the following lines.
bunfig.toml
happydom.ts when you run bun test. Now you can write tests that use browser APIs like document and window.
TypeScript Support
Depending on yourtsconfig.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.
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
Advanced DOM Testing
Custom Elements
You can test custom elements and web components using the same setup:Event Testing
Test DOM events and user interactions:Configuration Tips
Global Setup
For more complex DOM testing setups, you can create a more comprehensive preload file: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
beforeEachto reset the DOM state between tests - Avoid creating too many DOM elements in a single test
- Consider using
cleanupfunctions from testing libraries