Skip to main content
You can write and run browser tests with Bun’s test runner in conjunction with Happy DOM. Happy DOM implements mocked versions of browser APIs like document and location.
To get started, install happy-dom.
terminal

This module exports a “registrator” that injects the mocked browser APIs to the global scope.
happydom.ts

We need to make sure this file is executed before any of our test files. That’s a job for Bun’s built-in preload functionality. Create a bunfig.toml file in the root of your project (if it doesn’t already exist) and add the following lines. The ./happydom.ts file should contain the registration code above.
bunfig.toml

Now running bun test inside our project will automatically execute happydom.ts first. We can start writing tests that use browser APIs.
dom.test.ts

With Happy DOM properly configured, this test runs as expected.
terminal

Refer to the Happy DOM repo and Docs > Test runner > DOM for complete documentation on writing browser tests with Bun.