rembrembdocs

Skip to main content

Bun home pagelight logodark logo

[Runtime

](../../../index.md)[Package Manager

](../../../pm/cli/install/index.md)[Bundler

](../../../bundler/index.md)[Test Runner

](../../../test/index.md)[Guides

](../../index.md)[Reference

](https://bun.com/reference)[Blog

](https://bun.com/blog)[Feedback

](../../../feedback/index.md)

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

bun add -d @happy-dom/global-registrator

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

https://mintcdn.com/bun-1dd33a4e/JUhaF6Mf68z_zHyy/icons/typescript.svg?fit=max&auto=format&n=JUhaF6Mf68z_zHyy&q=85&s=7ac549adaea8d5487d8fbd58cc3ea35bhappydom.ts

import { GlobalRegistrator } from "@happy-dom/global-registrator";

GlobalRegistrator.register();

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

[test]
preload = "./happydom.ts"

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

https://mintcdn.com/bun-1dd33a4e/JUhaF6Mf68z_zHyy/icons/typescript.svg?fit=max&auto=format&n=JUhaF6Mf68z_zHyy&q=85&s=7ac549adaea8d5487d8fbd58cc3ea35bdom.test.ts

import { test, expect } from "bun:test";

test("set button text", () => {
  document.body.innerHTML = `<button>My button</button>`;
  const button = document.querySelector("button");
  expect(button?.innerText).toEqual("My button");
});

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

terminal

bun test

dom.test.ts:
✓ set button text [0.82ms]

 1 pass
 0 fail
 1 expect() calls
Ran 1 tests across 1 files. 1 total [125.00ms]

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

Was this page helpful?

Suggest editsRaise issue

[

Using Testing Library with Bun

Previous

](../testing-library/index.md)[

import, require, and test Svelte components with bun test

Next

](../svelte-test/index.md)