Skip to content
Ilha
Esc
↑↓navigate↵open⌘Jpreview
On this page

Test components

Test components with the ilha/test harness. Render, drive events, wait for idle, and assert on HTML or live state.

ilha/test mounts a component, drives it with events, and waits until it is idle. It has no timers and no test-runner imports, so it works under bun:test, Vitest, and node:test.

import { const atom: AtomFnatom } from "ilha";
import { const render: (fn: Component, opts?: RenderOptions) => TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
} from "ilha/test";
import { const expect: Expect
Asserts that a value matches some criteria.
@linkhttps://jestjs.io/docs/expect#reference@example```ts expect(1 + 1).toBe(2); expect([1,2,3]).toContain(2); expect(null).toBeNull(); ```@paramactual The actual (received) value
expect
, const test: Test<[]>
Runs a test.
@example```ts test("can check if using Bun", () => { expect(Bun).toBeDefined(); }); test("can make a fetch() request", async () => { const response = await fetch("https://example.com/"); expect(response.ok).toBe(true); }); ```@paramlabel the label for the test@paramfn the test function
test
} from "bun:test";
const const Counter: () => ViewCounter = () => { const const count: AtomHandle<number, number>count = atom<number>(init: number | Atom<number>, options?: AtomOptions<number> | undefined): AtomHandle<number, number> (+2 overloads)
An existing Effect atom, or a plain value. Store a function with `atom.lazy(() => fn)`; the `ilha/oxlint` rule `function-in-atom` flags `atom(fn)`.
atom
(0);
return ( <JSX.IntrinsicElements.button: ButtonHTMLAttributesbutton type?: string | undefinedtype="button" EventProps<HTMLButtonElement>.onclick?: ((event: Targeted<HTMLButtonElement, MouseEvent>) => void) | undefinedonclick={() => const count: AtomHandle<number, number>count.AtomHandle<number, number>.update: (f: (current: number) => number) => voidupdate((n: numbern) => n: numbern + 1)}> {const count: AtomHandle<number, number>count} </JSX.IntrinsicElements.button: ButtonHTMLAttributesbutton> ); }; function test(label: string, fn: (done: (err?: unknown) => void) => void | Promise<unknown>, options?: number | TestOptions): void (+1 overload)
Runs a test, with the options before the test function.
@example```ts test("can retry", { retry: 3 }, () => { expect(Math.random()).toBeLessThan(0.5); }); ```
test
("clicking increments", async () => {
const const ui: TestUiui = function render(fn: Component, opts?: RenderOptions): TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
(const Counter: () => ViewCounter);
await const ui: TestUiui.TestUi.click: (selector: string) => Promise<void>click("button"); expect<string>(actual: string, customFailMessage?: string): Matchers<string> (+2 overloads)
@paramactual the actual value@paramcustomFailMessage an optional custom message to display if the test fails.
expect
(const ui: TestUiui.TestUi.text: () => string
The container's `textContent`.
text
()).MatchersBuiltin<string>.toBe(expected: string): void (+1 overload)
Asserts that a value equals what is expected. - For non-primitive values, like objects and arrays, use `toEqual()` instead. - For floating-point numbers, use `toBeCloseTo()` instead.
@exampleexpect(100 + 23).toBe(123); expect("d" + "og").toBe("dog"); expect([123]).toBe([123]); // fail, use toEqual() expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo() // TypeScript errors: expect("hello").toBe(3.14); // typescript error + fail expect("hello").toBe<number>(3.14); // no typescript error, but still fails@paramexpected the expected value
toBe
("1");
const ui: TestUiui.TestUi.unmount: () => void
Stop the mount and remove a container the harness created.
unmount
();
});

render() mounts into a new <div> on document.body. Each action awaits ui.settled() before and after it runs, so you assert on the final DOM without sleeping.

Set up a DOM

render() needs DOM globals. It throws a clear error if document is missing. Preload happy-dom:

npm install -d @happy-dom/global-registrator
pnpm add -d @happy-dom/global-registrator
yarn add -d @happy-dom/global-registrator
bun add -d @happy-dom/global-registrator
nub add -d @happy-dom/global-registrator
aube add -d @happy-dom/global-registrator
# bunfig.toml
[test]
preload = "./happydom.ts"
// happydom.ts
import { class GlobalRegistratorGlobalRegistrator } from "@happy-dom/global-registrator";

class GlobalRegistratorGlobalRegistrator.
GlobalRegistrator.register(options?: {
    width?: number;
    height?: number;
    url?: string;
    settings?: IOptionalBrowserSettings;
}): void
Registers Happy DOM globally.
@paramoptions Options.@paramoptions.width Window width. Defaults to "1024".@paramoptions.height Window height. Defaults to "768".@paramoptions.url URL.@paramoptions.settings Settings.
register
();

For DOM-free HTML assertions, use renderHtml() instead.

Drive events

Every action takes a CSS selector and resolves after the mount is idle again. A selector that matches nothing throws an error that includes the current HTML.

Method What it does
await ui.click(selector) Fires a bubbling click.
await ui.input(selector, v) Sets value, then fires input.
await ui.change(selector, v) Sets value (or checked for a boolean), fires change.
await ui.submit(selector) Fires a cancelable submit.
await ui.dispatch(selector, e) Dispatches any Event you build.
import { const atom: AtomFnatom } from "ilha";
import { const render: (fn: Component, opts?: RenderOptions) => TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
} from "ilha/test";
import { const expect: Expect
Asserts that a value matches some criteria.
@linkhttps://jestjs.io/docs/expect#reference@example```ts expect(1 + 1).toBe(2); expect([1,2,3]).toContain(2); expect(null).toBeNull(); ```@paramactual The actual (received) value
expect
, const test: Test<[]>
Runs a test.
@example```ts test("can check if using Bun", () => { expect(Bun).toBeDefined(); }); test("can make a fetch() request", async () => { const response = await fetch("https://example.com/"); expect(response.ok).toBe(true); }); ```@paramlabel the label for the test@paramfn the test function
test
} from "bun:test";
const const Search: () => ViewSearch = () => { const const query: AtomHandle<string, string>query = atom<string>(init: string | Atom<string>, options?: AtomOptions<string> | undefined): AtomHandle<string, string> (+2 overloads)
An existing Effect atom, or a plain value. Store a function with `atom.lazy(() => fn)`; the `ilha/oxlint` rule `function-in-atom` flags `atom(fn)`.
atom
("");
return ( <JSX.IntrinsicElements.form: FormHTMLAttributesform EventProps<HTMLFormElement>.onsubmit?: ((event: Targeted<HTMLFormElement, SubmitEvent>) => void) | undefinedonsubmit={(event: Eventevent: Event) => event: Eventevent.Event.preventDefault(): void
The **`preventDefault()`** method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)
preventDefault
()}>
<JSX.IntrinsicElements.input: InputHTMLAttributesinput value?: Bindable<string | number> | undefinedvalue={
const query: AtomHandle
() => string
query
()}
EventProps<HTMLInputElement>.oninput?: ((event: Targeted<HTMLInputElement, Event>) => void) | undefinedoninput={(event: Eventevent: Event) => { if (event: Eventevent.Event.target: EventTarget | null
The read-only **`target`** property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)
target
instanceof
var HTMLInputElement: {
    new (): HTMLInputElement;
    prototype: HTMLInputElement;
}
The **`HTMLInputElement`** interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements. [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement)
HTMLInputElement
) {
const query: AtomHandle<string, string>query.AtomHandle<string, string>.set: (next: string) => voidset(event: Eventevent.Event.target: HTMLInputElement
The read-only **`target`** property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)
target
.HTMLInputElement.value: string
The **`value`** property of the HTMLInputElement interface represents the current value of the <input> element as a string. [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/value)
value
);
} }} /> <JSX.IntrinsicElements.output: OutputHTMLAttributesoutput>{
const query: AtomHandle
() => string
query
()}</JSX.IntrinsicElements.output: OutputHTMLAttributesoutput>
</JSX.IntrinsicElements.form: FormHTMLAttributesform> ); }; function test(label: string, fn: (done: (err?: unknown) => void) => void | Promise<unknown>, options?: number | TestOptions): void (+1 overload)
Runs a test, with the options before the test function.
@example```ts test("can retry", { retry: 3 }, () => { expect(Math.random()).toBeLessThan(0.5); }); ```
test
("typing updates the output", async () => {
const const ui: TestUiui = function render(fn: Component, opts?: RenderOptions): TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
(const Search: () => ViewSearch);
await const ui: TestUiui.TestUi.input: (selector: string, value: string) => Promise<void>
Set `value` on the element, then fire a bubbling `input` event.
input
("input", "ilha");
expect<string | undefined>(actual: string | undefined, customFailMessage?: string): Matchers<string | undefined> (+2 overloads)
@paramactual the actual value@paramcustomFailMessage an optional custom message to display if the test fails.
expect
(const ui: TestUiui.TestUi.query: <Element>(selector: string) => Element | nullquery("output")?.Element.textContent: string | undefined
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/textContent)
textContent
).MatchersBuiltin<string | undefined>.toBe(expected: string | undefined): void (+1 overload)
Asserts that a value equals what is expected. - For non-primitive values, like objects and arrays, use `toEqual()` instead. - For floating-point numbers, use `toBeCloseTo()` instead.
@exampleexpect(100 + 23).toBe(123); expect("d" + "og").toBe("dog"); expect([123]).toBe([123]); // fail, use toEqual() expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo() // TypeScript errors: expect("hello").toBe(3.14); // typescript error + fail expect("hello").toBe<number>(3.14); // no typescript error, but still fails@paramexpected the expected value
toBe
("ilha");
const ui: TestUiui.TestUi.unmount: () => void
Stop the mount and remove a container the harness created.
unmount
();
});

Wait for idle

await ui.settled() resolves once the mount has no pending work: the first paint, rerenders, async components, and watchers. It resolves immediately if the mount is already idle.

import { const render: (fn: Component, opts?: RenderOptions) => TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
} from "ilha/test";
import { const expect: Expect
Asserts that a value matches some criteria.
@linkhttps://jestjs.io/docs/expect#reference@example```ts expect(1 + 1).toBe(2); expect([1,2,3]).toContain(2); expect(null).toBeNull(); ```@paramactual The actual (received) value
expect
, const test: Test<[]>
Runs a test.
@example```ts test("can check if using Bun", () => { expect(Bun).toBeDefined(); }); test("can make a fetch() request", async () => { const response = await fetch("https://example.com/"); expect(response.ok).toBe(true); }); ```@paramlabel the label for the test@paramfn the test function
test
} from "bun:test";
const const Greeting: () => Promise<View>Greeting = async () => { await var Promise: PromiseConstructor
Represents the completion of an asynchronous operation
Promise
.PromiseConstructor.resolve(): Promise<void> (+2 overloads)
Creates a new resolved promise.
@returnsA resolved promise.
resolve
();
return <JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>hello</JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>; }; function test(label: string, fn: (done: (err?: unknown) => void) => void | Promise<unknown>, options?: number | TestOptions): void (+1 overload)
Runs a test, with the options before the test function.
@example```ts test("can retry", { retry: 3 }, () => { expect(Math.random()).toBeLessThan(0.5); }); ```
test
("async components settle", async () => {
const const ui: TestUiui = function render(fn: Component, opts?: RenderOptions): TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
(const Greeting: () => Promise<View>Greeting);
await const ui: TestUiui.TestUi.settled: () => Promise<void>
Resolves when the mount has no pending work left. Never uses timers.
settled
();
expect<string>(actual: string, customFailMessage?: string): Matchers<string> (+2 overloads)
@paramactual the actual value@paramcustomFailMessage an optional custom message to display if the test fails.
expect
(const ui: TestUiui.TestUi.text: () => string
The container's `textContent`.
text
()).MatchersBuiltin<string>.toBe(expected: string): void (+1 overload)
Asserts that a value equals what is expected. - For non-primitive values, like objects and arrays, use `toEqual()` instead. - For floating-point numbers, use `toBeCloseTo()` instead.
@exampleexpect(100 + 23).toBe(123); expect("d" + "og").toBe("dog"); expect([123]).toBe([123]); // fail, use toEqual() expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo() // TypeScript errors: expect("hello").toBe(3.14); // typescript error + fail expect("hello").toBe<number>(3.14); // no typescript error, but still fails@paramexpected the expected value
toBe
("hello");
const ui: TestUiui.TestUi.unmount: () => void
Stop the mount and remove a container the harness created.
unmount
();
});

Read the DOM

Method Returns
ui.html() The container’s innerHTML.
ui.text() The container’s textContent.
ui.query(selector) The first matching element or null.
ui.queryAll(selector) An array of matching elements.
ui.errors Errors the mount reported to onError.

query() and queryAll() accept an element type: ui.query<HTMLInputElement>("input").

Inspect live state

ui.tree() returns the JSON tree that ilha/debug produces for this mount. ui.atoms() flattens it to every atom, in render order.

import { const atom: AtomFnatom } from "ilha";
import { const render: (fn: Component, opts?: RenderOptions) => TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
} from "ilha/test";
import { const expect: Expect
Asserts that a value matches some criteria.
@linkhttps://jestjs.io/docs/expect#reference@example```ts expect(1 + 1).toBe(2); expect([1,2,3]).toContain(2); expect(null).toBeNull(); ```@paramactual The actual (received) value
expect
, const test: Test<[]>
Runs a test.
@example```ts test("can check if using Bun", () => { expect(Bun).toBeDefined(); }); test("can make a fetch() request", async () => { const response = await fetch("https://example.com/"); expect(response.ok).toBe(true); }); ```@paramlabel the label for the test@paramfn the test function
test
} from "bun:test";
const const Counter: () => ViewCounter = () => { const const count: AtomHandle<number, number>count = atom<number>(init: number | Atom<number>, options?: AtomOptions<number> | undefined): AtomHandle<number, number> (+2 overloads)
An existing Effect atom, or a plain value. Store a function with `atom.lazy(() => fn)`; the `ilha/oxlint` rule `function-in-atom` flags `atom(fn)`.
atom
(0);
return ( <JSX.IntrinsicElements.button: ButtonHTMLAttributesbutton type?: string | undefinedtype="button" EventProps<HTMLButtonElement>.onclick?: ((event: Targeted<HTMLButtonElement, MouseEvent>) => void) | undefinedonclick={() => const count: AtomHandle<number, number>count.AtomHandle<number, number>.update: (f: (current: number) => number) => voidupdate((n: numbern) => n: numbern + 1)}> {const count: AtomHandle<number, number>count} </JSX.IntrinsicElements.button: ButtonHTMLAttributesbutton> ); }; function test(label: string, fn: (done: (err?: unknown) => void) => void | Promise<unknown>, options?: number | TestOptions): void (+1 overload)
Runs a test, with the options before the test function.
@example```ts test("can retry", { retry: 3 }, () => { expect(Math.random()).toBeLessThan(0.5); }); ```
test
("state is observable", async () => {
const const ui: TestUiui = function render(fn: Component, opts?: RenderOptions): TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
(const Counter: () => ViewCounter);
await const ui: TestUiui.TestUi.click: (selector: string) => Promise<void>click("button"); expect<AtomEntry[]>(actual: AtomEntry[], customFailMessage?: string): Matchers<AtomEntry[]> (+2 overloads)
@paramactual the actual value@paramcustomFailMessage an optional custom message to display if the test fails.
expect
(const ui: TestUiui.TestUi.atoms: () => AtomEntry[]
Every atom in the tree, in render order.
atoms
()).MatchersBuiltin<AtomEntry[]>.toEqual(expected: AtomEntry[]): void (+1 overload)
Asserts that a value is deeply equal to what is expected.
@exampleexpect(100 + 23).toBe(123); expect("d" + "og").toBe("dog"); expect([456]).toEqual([456]); expect({ value: 1 }).toEqual({ value: 1 });@paramexpected the expected value
toEqual
([{ AtomEntry.component: string
Name of the component that owns the atom.
component
: "Counter", AtomEntry.index: number
Slot index, in registration order.
index
: 0, AtomEntry.value: SnapshotValuevalue: 1 }]);
const ui: TestUiui.TestUi.unmount: () => void
Stop the mount and remove a container the harness created.
unmount
();
});

Assert on atom values when the DOM hides the state you care about.

Test server rendering

renderHtml() wraps renderToString and returns the server HTML. Two renders of the same component must match byte for byte:

import { const atom: AtomFnatom } from "ilha";
import { const renderHtml: (fn: Component, opts?: RenderToStringOptions) => Promise<string>
Render `fn` to HTML without a DOM. Same output as `renderToString`, kept here so tests import both helpers from `ilha/test`.
renderHtml
} from "ilha/test";
import { const expect: Expect
Asserts that a value matches some criteria.
@linkhttps://jestjs.io/docs/expect#reference@example```ts expect(1 + 1).toBe(2); expect([1,2,3]).toContain(2); expect(null).toBeNull(); ```@paramactual The actual (received) value
expect
, const test: Test<[]>
Runs a test.
@example```ts test("can check if using Bun", () => { expect(Bun).toBeDefined(); }); test("can make a fetch() request", async () => { const response = await fetch("https://example.com/"); expect(response.ok).toBe(true); }); ```@paramlabel the label for the test@paramfn the test function
test
} from "bun:test";
const const Counter: () => ViewCounter = () => { const const count: AtomHandle<number, number>count = atom<number>(init: number | Atom<number>, options?: AtomOptions<number> | undefined): AtomHandle<number, number> (+2 overloads)
An existing Effect atom, or a plain value. Store a function with `atom.lazy(() => fn)`; the `ilha/oxlint` rule `function-in-atom` flags `atom(fn)`.
atom
(0);
return <JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>{const count: AtomHandle<number, number>count}</JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>; }; function test(label: string, fn: (done: (err?: unknown) => void) => void | Promise<unknown>, options?: number | TestOptions): void (+1 overload)
Runs a test, with the options before the test function.
@example```ts test("can retry", { retry: 3 }, () => { expect(Math.random()).toBeLessThan(0.5); }); ```
test
("server output is stable", async () => {
expect<string>(actual: string, customFailMessage?: string): Matchers<string> (+2 overloads)
@paramactual the actual value@paramcustomFailMessage an optional custom message to display if the test fails.
expect
(await function renderHtml(fn: Component, opts?: RenderToStringOptions): Promise<string>
Render `fn` to HTML without a DOM. Same output as `renderToString`, kept here so tests import both helpers from `ilha/test`.
renderHtml
(const Counter: () => ViewCounter)).MatchersBuiltin<string>.toBe(expected: string): void (+1 overload)
Asserts that a value equals what is expected. - For non-primitive values, like objects and arrays, use `toEqual()` instead. - For floating-point numbers, use `toBeCloseTo()` instead.
@exampleexpect(100 + 23).toBe(123); expect("d" + "og").toBe("dog"); expect([123]).toBe([123]); // fail, use toEqual() expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo() // TypeScript errors: expect("hello").toBe(3.14); // typescript error + fail expect("hello").toBe<number>(3.14); // no typescript error, but still fails@paramexpected the expected value
toBe
(await function renderHtml(fn: Component, opts?: RenderToStringOptions): Promise<string>
Render `fn` to HTML without a DOM. Same output as `renderToString`, kept here so tests import both helpers from `ilha/test`.
renderHtml
(const Counter: () => ViewCounter));
});

Test hydration

Pass ssr: true to render on the server, inject the HTML into the container, and hydrate it. Await ui.settled() before you read the DOM, because the server render is async.

import { const atom: AtomFnatom } from "ilha";
import { const render: (fn: Component, opts?: RenderOptions) => TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
} from "ilha/test";
import { const expect: Expect
Asserts that a value matches some criteria.
@linkhttps://jestjs.io/docs/expect#reference@example```ts expect(1 + 1).toBe(2); expect([1,2,3]).toContain(2); expect(null).toBeNull(); ```@paramactual The actual (received) value
expect
, const test: Test<[]>
Runs a test.
@example```ts test("can check if using Bun", () => { expect(Bun).toBeDefined(); }); test("can make a fetch() request", async () => { const response = await fetch("https://example.com/"); expect(response.ok).toBe(true); }); ```@paramlabel the label for the test@paramfn the test function
test
} from "bun:test";
const const Counter: () => ViewCounter = () => { const const count: AtomHandle<number, number>count = atom<number>(init: number | Atom<number>, options?: AtomOptions<number> | undefined): AtomHandle<number, number> (+2 overloads)
An existing Effect atom, or a plain value. Store a function with `atom.lazy(() => fn)`; the `ilha/oxlint` rule `function-in-atom` flags `atom(fn)`.
atom
(0);
return ( <JSX.IntrinsicElements.button: ButtonHTMLAttributesbutton type?: string | undefinedtype="button" EventProps<HTMLButtonElement>.onclick?: ((event: Targeted<HTMLButtonElement, MouseEvent>) => void) | undefinedonclick={() => const count: AtomHandle<number, number>count.AtomHandle<number, number>.update: (f: (current: number) => number) => voidupdate((n: numbern) => n: numbern + 1)}> {const count: AtomHandle<number, number>count} </JSX.IntrinsicElements.button: ButtonHTMLAttributesbutton> ); }; function test(label: string, fn: (done: (err?: unknown) => void) => void | Promise<unknown>, options?: number | TestOptions): void (+1 overload)
Runs a test, with the options before the test function.
@example```ts test("can retry", { retry: 3 }, () => { expect(Math.random()).toBeLessThan(0.5); }); ```
test
("hydrated markup stays interactive", async () => {
const const ui: TestUiui = function render(fn: Component, opts?: RenderOptions): TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
(const Counter: () => ViewCounter, { RenderOptions.ssr?: boolean | undefined
Render on the server first and inject the HTML into the container. Default `false`.
ssr
: true });
await const ui: TestUiui.TestUi.settled: () => Promise<void>
Resolves when the mount has no pending work left. Never uses timers.
settled
();
await const ui: TestUiui.TestUi.click: (selector: string) => Promise<void>click("button"); expect<string>(actual: string, customFailMessage?: string): Matchers<string> (+2 overloads)
@paramactual the actual value@paramcustomFailMessage an optional custom message to display if the test fails.
expect
(const ui: TestUiui.TestUi.text: () => string
The container's `textContent`.
text
()).MatchersBuiltin<string>.toBe(expected: string): void (+1 overload)
Asserts that a value equals what is expected. - For non-primitive values, like objects and arrays, use `toEqual()` instead. - For floating-point numbers, use `toBeCloseTo()` instead.
@exampleexpect(100 + 23).toBe(123); expect("d" + "og").toBe("dog"); expect([123]).toBe([123]); // fail, use toEqual() expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo() // TypeScript errors: expect("hello").toBe(3.14); // typescript error + fail expect("hello").toBe<number>(3.14); // no typescript error, but still fails@paramexpected the expected value
toBe
("1");
const ui: TestUiui.TestUi.unmount: () => void
Stop the mount and remove a container the harness created.
unmount
();
});

To check that hydration keeps the server nodes, fill the container yourself and pass hydrate: true:

import { const atom: AtomFnatom } from "ilha";
import { const render: (fn: Component, opts?: RenderOptions) => TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
, const renderHtml: (fn: Component, opts?: RenderToStringOptions) => Promise<string>
Render `fn` to HTML without a DOM. Same output as `renderToString`, kept here so tests import both helpers from `ilha/test`.
renderHtml
} from "ilha/test";
import { const expect: Expect
Asserts that a value matches some criteria.
@linkhttps://jestjs.io/docs/expect#reference@example```ts expect(1 + 1).toBe(2); expect([1,2,3]).toContain(2); expect(null).toBeNull(); ```@paramactual The actual (received) value
expect
, const test: Test<[]>
Runs a test.
@example```ts test("can check if using Bun", () => { expect(Bun).toBeDefined(); }); test("can make a fetch() request", async () => { const response = await fetch("https://example.com/"); expect(response.ok).toBe(true); }); ```@paramlabel the label for the test@paramfn the test function
test
} from "bun:test";
const const Counter: () => ViewCounter = () => { const const count: AtomHandle<number, number>count = atom<number>(init: number | Atom<number>, options?: AtomOptions<number> | undefined): AtomHandle<number, number> (+2 overloads)
An existing Effect atom, or a plain value. Store a function with `atom.lazy(() => fn)`; the `ilha/oxlint` rule `function-in-atom` flags `atom(fn)`.
atom
(0);
return <JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>{const count: AtomHandle<number, number>count}</JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>; }; function test(label: string, fn: (done: (err?: unknown) => void) => void | Promise<unknown>, options?: number | TestOptions): void (+1 overload)
Runs a test, with the options before the test function.
@example```ts test("can retry", { retry: 3 }, () => { expect(Math.random()).toBeLessThan(0.5); }); ```
test
("hydration reuses server nodes", async () => {
const const container: HTMLDivElementcontainer = var document: Document
**`window.document`** returns a reference to the document contained in the window. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)
document
.Document.createElement<"div">(tagName: "div", options?: ElementCreationOptions): HTMLDivElement (+2 overloads)
In an HTML document, the **`document.createElement()`** method creates the HTML element specified by localName, or an HTMLUnknownElement if localName isn't recognized. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElement)
createElement
("div");
var document: Document
**`window.document`** returns a reference to the document contained in the window. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)
document
.Document.body: HTMLElement
The **`Document.body`** property represents the <body> or <frameset> node of the current document, or null if no such element exists. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/body)
body
.ParentNode.append(...nodes: (Node | string)[]): void
Inserts nodes after the last child of node, while replacing strings in nodes with equivalent Text nodes. Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/append)
append
(const container: HTMLDivElementcontainer);
const container: HTMLDivElementcontainer.Element.innerHTML: string
The **`innerHTML`** property of the Element interface gets or sets the HTML or XML markup contained within the element, omitting any shadow roots in both cases. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/innerHTML)
innerHTML
= await function renderHtml(fn: Component, opts?: RenderToStringOptions): Promise<string>
Render `fn` to HTML without a DOM. Same output as `renderToString`, kept here so tests import both helpers from `ilha/test`.
renderHtml
(const Counter: () => ViewCounter);
const const serverNode: HTMLParagraphElement | nullserverNode = const container: HTMLDivElementcontainer.ParentNode.querySelector<"p">(selectors: "p"): HTMLParagraphElement | null (+4 overloads)
Returns the first element that is a descendant of node that matches selectors. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/querySelector)
querySelector
("p");
const const ui: TestUiui = function render(fn: Component, opts?: RenderOptions): TestUi
Mount `fn` into a DOM container and return a handle that drives it. Needs a DOM global (happy-dom). With `ssr`, the server render is async: `await ui.settled()` before reading `html()`.
render
(const Counter: () => ViewCounter, { RenderOptions.container?: Element | undefined
Mount into this element. Default: a new `<div>` appended to `document.body`.
container
, RenderOptions.hydrate?: boolean | undefined
Hydrate the container instead of mounting fresh. Default: the value of `ssr`. With `hydrate: true` alone, the container must already hold server markup.
hydrate
: true });
await const ui: TestUiui.TestUi.settled: () => Promise<void>
Resolves when the mount has no pending work left. Never uses timers.
settled
();
expect<Element | null>(actual: Element | null, customFailMessage?: string): Matchers<Element | null> (+2 overloads)
@paramactual the actual value@paramcustomFailMessage an optional custom message to display if the test fails.
expect
(const ui: TestUiui.TestUi.query: <Element>(selector: string) => Element | nullquery("p")).MatchersBuiltin<Element | null>.toBe(expected: Element | null): void (+1 overload)
Asserts that a value equals what is expected. - For non-primitive values, like objects and arrays, use `toEqual()` instead. - For floating-point numbers, use `toBeCloseTo()` instead.
@exampleexpect(100 + 23).toBe(123); expect("d" + "og").toBe("dog"); expect([123]).toBe([123]); // fail, use toEqual() expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo() // TypeScript errors: expect("hello").toBe(3.14); // typescript error + fail expect("hello").toBe<number>(3.14); // no typescript error, but still fails@paramexpected the expected value
toBe
(const serverNode: HTMLParagraphElement | nullserverNode);
const ui: TestUiui.TestUi.unmount: () => void
Stop the mount and remove a container the harness created.
unmount
();
const container: HTMLDivElementcontainer.ChildNode.remove(): void
Removes node. [MDN Reference](https://developer.mozilla.org/docs/Web/API/CharacterData/remove)
remove
();
});

Options

Option Default Effect
ssr false Render on the server first and inject the HTML.
hydrate same as ssr Hydrate the container. With ssr: true, hydrate: false the HTML stays static.
container new <div> Mount into your element. unmount() leaves it in the document.
onError none Called for uncaught component failures. They also land in ui.errors.

Call ui.unmount() at the end of each test. It stops listeners and removes a container the harness created.

Topic Guide
Render and hydrate Render
Streams in tests Streams
Inspect live state Devtools

Was this page helpful?