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
document available in the global scope. Create a file called happydom.ts in the root of your project with the following code:
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.
TypeScript Support
Depending on yourtsconfig.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.
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
Advanced DOM Testing
Custom Elements
Test custom elements and web components with the same setup:Event Testing
Test DOM events and user interactions:Configuration Tips
Global Setup
For more involved setups, create a preload file that also registers global mocks: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
beforeEachto reset the DOM state between tests - Avoid creating too many DOM elements in a single test
- Use
cleanupfunctions from testing libraries