Skip to content

Testing

Test signals, components, server-rendered HTML and resources with the same tools Xote uses for its own tests.

docs/guides/testing.md
Raw Markdown

This guide sets up a small test suite for a Xote app: plain tests for your state, DOM tests for components, string tests for server rendering, and async tests for resources. It uses the same tools Xote uses for its own tests.

Set up the tools

Xote's own suite runs on Zekr, a ReScript test library with DOM queries and events, and jsdom, which gives Node a browser-like document. Tests are plain ReScript files you run with node, no extra runner needed.

1npm install --save-dev zekr jsdom

Add Zekr as a dev dependency and a tests folder as a dev source in rescript.json:

1{
2 "sources": [
3 { "dir": "src", "subdirs": true },
4 { "dir": "tests", "subdirs": true, "type": "dev" }
5 ],
6 "dependencies": ["xote"],
7 "dev-dependencies": ["zekr"]
8}

Keep your existing jsx, ppx-flags and compiler-flags settings as they are.

Create tests/setup.mjs. It puts jsdom's window on the global object, so Xote finds a DOM:

1import { JSDOM } from 'jsdom'
2
3const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
4 url: 'http://localhost/',
5})
6
7globalThis.window = dom.window
8globalThis.document = dom.window.document
9globalThis.Node = dom.window.Node
10globalThis.HTMLElement = dom.window.HTMLElement
11globalThis.Event = dom.window.Event
12globalThis.MouseEvent = dom.window.MouseEvent
13globalThis.KeyboardEvent = dom.window.KeyboardEvent
14globalThis.InputEvent = dom.window.InputEvent

Then an entry file that runs your suites:

1// tests/Tests.res
2Zekr.runSuites([Counter_test.suite])

And a script in package.json that loads the setup before anything else with Node's --import flag:

1{
2 "scripts": {
3 "test": "rescript && node --import ./tests/setup.mjs tests/Tests.res.mjs"
4 }
5}

Test state without a DOM

Signals, computeds and effects are ordinary values. Create them, change them, and check the result:

1// tests/Counter_test.res
2open! Zekr
3
4let suite = suite(
5 "Counter",
6 [
7 test("a computed follows its signal", () => {
8 let count = Signal.make(2)
9 let doubled = Computed.make(() => Signal.get(count) * 2)
10 Signal.set(count, 5)
11 assertEqual(Signal.peek(doubled), 10)
12 }),
13 ],
14)

Use Signal.peek in assertions. It reads the value without subscribing anything.

For an effect, record what it sees, and dispose it at the end so it stops reacting to later tests:

1test("an effect re-runs when its signal changes", () => {
2 let name = Signal.make("Ada")
3 let seen = []
4 let effect = Effect.runWithDisposer(() => {
5 seen->Array.push(Signal.get(name))
6 None
7 })
8 Signal.set(name, "Grace")
9 effect.dispose()
10 assertEqual(seen, ["Ada", "Grace"])
11}),

The same pattern checks batching: two writes inside Signal.batch should make the effect run once more, not twice.

Render a component and interact with it

Dom.render("") gives you an empty container in the document. Mount your component into it, find elements the way a user would, fire events, and assert on the DOM:

1// src/Counter.res
2@xote.component
3let make = (~start=0) => {
4 let count = Signal.make(start)
5 <button onClick={_ => Signal.update(count, n => n + 1)}> {"Clicked "} {Signal.get(count)} </button>
6}
1test("clicking the button counts up", () => {
2 let {container} = Dom.render("")
3 View.mount(<Counter start=1 />, container)
4 let button = Dom.Query.getByRole(container, "button")
5 Dom.Event.click(button)
6 Dom.Assert.toHaveTextContent(button, "Clicked 2")
7}),

Updates are synchronous, so the DOM is current as soon as the click returns. There is no need to wait.

Dom.Query also has getByText, getByLabelText, getByPlaceholder and getByTestId. Dom.Event has typeText, clear, check and selectOptions for forms. Pass ~afterEach=Dom.cleanup to suite to remove each test's container when it ends.

Info: After open! Zekr, Dom means Zekr's DOM helpers. If you need the standard Dom.element type in a test file, alias it before the open: type domElement = Dom.element.

Check server-rendered HTML

SSR.renderToString returns the HTML a component produces on the server. Assert on the parts you care about rather than the whole string, because the output includes hydration markers:

1test("renders on the server", () => {
2 let html = SSR.renderToString(() => <Counter start=3 />)
3 assertContains(html, "Clicked ")
4}),

Test resources and other async code

New in 7.2

Async tests use asyncTest and asyncSuite. To let a promise settle, wait one tick:

1// tests/Async_test.res
2open! Zekr
3
4let settle = () => Promise.make((resolve, _) => setTimeout(() => resolve(), 0)->ignore)
5
6let suite = asyncSuite(
7 "Resources",
8 [
9 asyncTest("a resource settles as Ready", async () => {
10 let user = Resource.make(() => Promise.resolve("Ada"))
11 let before = Signal.peek(user)
12 await settle()
13 combineResults([
14 assertEqual(before, Resource.Pending),
15 assertEqual(Signal.peek(user), Resource.Ready("Ada")),
16 ])
17 }),
18 ],
19)

Run async suites from their own entry file with runAsyncSuites, because the synchronous runner ends the process once it reports:

1// tests/AsyncTests.res
2Zekr.runAsyncSuites([Async_test.suite])->ignore
1"test": "rescript && node --import ./tests/setup.mjs tests/Tests.res.mjs && node --import ./tests/setup.mjs tests/AsyncTests.res.mjs"

To control exactly when a fetch answers, return a promise you resolve by hand from the test. Xote's own resource tests do this to check loading, refreshing and stale responses.

Common mistakes

  • Loading the setup from inside a test file. Xote checks for a DOM once, when it loads, and ReScript places a %%raw(`import …`) after the file's own imports, so it runs too late. Load the setup with node --import ./tests/setup.mjs instead.
  • Leaving effects running. An effect created in a test lives until it's disposed. Use Effect.runWithDisposer and call dispose().
  • Sharing module-level signals between tests. Create fresh signals inside each test, or reset them, so one test can't leak into the next.
  • Comparing full SSR strings. Markers like <!--#--> are part of the output. Check for the content you care about.

Summary

Test Xote code with Zekr (a ReScript test library with DOM queries, events and assertions) on Node with jsdom providing document. This is the setup Xote's own suite (tests/ in the repo) uses. Signal, computed, effect and DOM updates are synchronous, so assertions can follow a Signal.set or a dispatched event directly; resources settle on promise ticks and need an await. The one rule that matters most: load jsdom before any Xote module is evaluated (preload it with node --import), because SSRContext.isServer/isClient are decided once, at module load.

Availability

ItemImport / entryFirst stableChanged in 7.2.0Needs the PPX
Signal, Computed, Effect.runWithDisposer, Signal.batchxotestable (all 7.x)—No
View.mount, SSR.renderToStringxote, xote/ssr7.0.0—No
Resource (async tests)xote7.2.0 (new)—No
Zekr (tested with 1.7.0)npm zekr, ReScript dependency zekrexternal——
jsdomnpm jsdomexternal——

Rules

  1. Install zekr and jsdom as dev dependencies, add "zekr" to "dev-dependencies" in rescript.json, and declare the test folder as a dev source ({"dir": "tests", "subdirs": true, "type": "dev"}).
  2. jsdom MUST be installed on globalThis (window, document, Node, HTMLElement, Event, MouseEvent, KeyboardEvent, InputEvent) before Xote's modules evaluate. Preload the setup file with node --import ./tests/setup.mjs ….
  3. %%raw(import './setup.mjs') at the top of a ReScript entry is emitted after the entry's module imports, so Xote's modules load before jsdom exists and SSRContext.isServer is true for the whole run. DOM rendering still works (it reads document at call time), but code guarded by SSRContext.isClient does not run and SSRState.register records values as if on the server. Use --import when the test depends on isClient.
  4. Zekr.runSuites (synchronous) exits the process when it reports. Async suites MUST run from a separate entry with Zekr.runAsyncSuites.
  5. Signal writes propagate synchronously: computeds read with Signal.peek are current, effects have run, and DOM reactive leaves are updated when Signal.set/Signal.update returns, and when a dispatched DOM event's handler returns.
  6. Inside Signal.batch, dependents are notified once, when the outermost batch returns.
  7. An effect created in a test (outside a component) has no owner and runs until disposed. Create it with Effect.runWithDisposer and call .dispose() before the test ends.
  8. Module-level signals keep their values across tests in the same process. Create signals inside the test, or reset them in ~beforeEach.
  9. Dom.render(html) appends a fresh container div to document.body and returns {container, baseElement}. Mount components into container with View.mount. Pass ~afterEach=Dom.cleanup to suite to remove containers between tests.
  10. A resource settles after its promise resolves: await a macrotask (setTimeout(_, 0)) before asserting on its state. For deterministic ordering, return promises whose resolvers the test controls.
  11. After open! Zekr, Dom refers to Zekr's DOM helpers and the standard Dom.element/Dom.event types are hidden. Alias them before the open (type domElement = Dom.element).
  12. Assert on SSR output with assertContains (substrings), not full-string equality: the HTML contains hydration markers whose exact form is an implementation detail.

API

NameSignatureBehaviour
Zekr.test(string, unit => testResult) => testCaseSynchronous test.
Zekr.asyncTest(string, unit => promise<testResult>, ~timeout: int=?) => asyncTestCaseAsync test.
Zekr.suite(string, array<testCase>, ~beforeAll=?, ~afterAll=?, ~beforeEach=?, ~afterEach=?) => testSuiteGroup with hooks.
Zekr.asyncSuitesame, with promise<unit> hooksAsync group.
Zekr.runSuites / runAsyncSuitesarray<testSuite> => unit / array<asyncTestSuite> => promise<unit>Run, report, and exit with status 0 or 1.
assertEqual, assertTrue, assertFalse, assertContains, assertSome, assertNone, assertThrowsassertions returning testResultStructural equality, substring, option checks.
combineResultsarray<testResult> => testResultSeveral assertions in one test.
Dom.renderstring => {container: Dom.element, baseElement: Dom.element}Fresh container in the document.
Dom.cleanupunit => unitRemoves containers created by render.
Dom.Query.getByRole / getByText / getByLabelText / getByPlaceholder / getByTestId / getByDisplayValue (+ queryBy…, getAllBy…)(Dom.element, string, …) => Dom.elementFind elements like a user; queryBy… returns option.
Dom.Event.click / typeText / clear / check / uncheck / selectOptions / focus / blurDom.element => unit (plus text/values)Dispatch realistic events (typeText fires keydown/input/keyup per character, then change).
Dom.Assert.toHaveTextContent / toHaveAttribute / toHaveClass / toBeInTheDocument… => testResultDOM assertions.
Effect.runWithDisposer(unit => option<unit => unit>, ~name: string=?) => {dispose: unit => unit}Effect you can stop.
SSR.renderToString(unit => View.node, ~options=?) => stringHTML string of a tree.

Patterns

Setup — Use when: adding tests to a project.

1npm install --save-dev zekr jsdom
1{
2 "sources": [
3 { "dir": "src", "subdirs": true },
4 { "dir": "tests", "subdirs": true, "type": "dev" }
5 ],
6 "dependencies": ["xote"],
7 "dev-dependencies": ["zekr"]
8}
1// tests/setup.mjs
2import { JSDOM } from 'jsdom'
3
4const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', { url: 'http://localhost/' })
5globalThis.window = dom.window
6globalThis.document = dom.window.document
7globalThis.Node = dom.window.Node
8globalThis.HTMLElement = dom.window.HTMLElement
9globalThis.Event = dom.window.Event
10globalThis.MouseEvent = dom.window.MouseEvent
11globalThis.KeyboardEvent = dom.window.KeyboardEvent
12globalThis.InputEvent = dom.window.InputEvent
1// tests/Tests.res
2Zekr.runSuites([Counter_test.suite])
1// tests/AsyncTests.res
2Zekr.runAsyncSuites([Async_test.suite])->ignore
1{
2 "scripts": {
3 "test": "rescript && node --import ./tests/setup.mjs tests/Tests.res.mjs && node --import ./tests/setup.mjs tests/AsyncTests.res.mjs"
4 }
5}

State, effects and batching without a DOM — Use when: testing logic in state/ modules.

1open! Zekr
2
3let suite = suite(
4 "State",
5 [
6 test("a computed follows its signal", () => {
7 let count = Signal.make(2)
8 let doubled = Computed.make(() => Signal.get(count) * 2)
9 Signal.set(count, 5)
10 assertEqual(Signal.peek(doubled), 10)
11 }),
12 test("an effect runs once per batch", () => {
13 let a = Signal.make(1)
14 let b = Signal.make(2)
15 let runs = ref(0)
16 let effect = Effect.runWithDisposer(() => {
17 let _ = Signal.get(a) + Signal.get(b)
18 runs := runs.contents + 1
19 None
20 })
21 Signal.batch(() => {
22 Signal.set(a, 10)
23 Signal.set(b, 20)
24 })
25 effect.dispose()
26 Signal.set(a, 99) // disposed: no further run
27 assertEqual(runs.contents, 2)
28 }),
29 ],
30)

Component interaction — Use when: testing what a user sees and does.

1// src/Counter.res
2@xote.component
3let make = (~start=0) => {
4 let count = Signal.make(start)
5 <button onClick={_ => Signal.update(count, n => n + 1)}> {"Clicked "} {Signal.get(count)} </button>
6}
1// tests/Counter_test.res
2open! Zekr
3
4let suite = suite(
5 "Counter",
6 [
7 test("clicking counts up", () => {
8 let {container} = Dom.render("")
9 View.mount(<Counter start=1 />, container)
10 let button = Dom.Query.getByRole(container, "button")
11 Dom.Event.click(button)
12 Dom.Assert.toHaveTextContent(button, "Clicked 2")
13 }),
14 test("renders on the server", () => {
15 let html = SSR.renderToString(() => <Counter start=3 />)
16 assertContains(html, "Clicked ")
17 }),
18 ],
19 ~afterEach=Dom.cleanup,
20)

Resources and stale responses (7.2.0) — Use when: testing data loading.

1open! Zekr
2
3let settle = () => Promise.make((resolve, _) => setTimeout(() => resolve(), 0)->ignore)
4
5let suite = asyncSuite(
6 "Resources",
7 [
8 asyncTest("settles as Ready", async () => {
9 let user = Resource.make(() => Promise.resolve("Ada"))
10 let before = Signal.peek(user)
11 await settle()
12 combineResults([
13 assertEqual(before, Resource.Pending),
14 assertEqual(Signal.peek(user), Resource.Ready("Ada")),
15 ])
16 }),
17 asyncTest("a later dependency change wins", async () => {
18 let id = Signal.make(1)
19 let resolvers: array<string => unit> = []
20 let user = Resource.make(() => {
21 let n = Signal.get(id)
22 Promise.make((resolve, _) => resolvers->Array.push(v => resolve(v ++ Int.toString(n)))->ignore)
23 })
24 Signal.set(id, 2)
25 (resolvers->Array.getUnsafe(1))("user")
26 await settle()
27 (resolvers->Array.getUnsafe(0))("user")
28 await settle()
29 assertEqual(Signal.peek(user), Resource.Ready("user2"))
30 }),
31 ],
32)

Anti-patterns

  1. Relying on %%raw to load jsdom first. Wrong: %%raw(import './setup.mjs') as the first line of Tests.res, run with node tests/Tests.res.mjs. Symptom: rendering works, but SSRContext.isClient is false, so if SSRContext.isClient { … } branches never run in tests and SSRState.register behaves as on a server. Right: node --import ./tests/setup.mjs tests/Tests.res.mjs. Why: ReScript emits module imports before raw top-level code; ES modules evaluate imports first.

  2. Undisposed effects. Wrong: Effect.run(() => { log->Array.push(Signal.get(name)); None }) in a test. Symptom: later tests that set name (or a shared signal) trigger the old effect; counts drift between runs. Right: let e = Effect.runWithDisposer(…) and e.dispose().

  3. Async suites in the sync entry. Wrong: Zekr.runSuites([...]) followed by Zekr.runAsyncSuites([...]) in one file. Symptom: async tests never run; the process exits after the sync report. Right: separate entry files.

  4. Asserting a resource immediately. Wrong: Resource.make(…) then assertEqual(Signal.peek(r), Ready(…)) without awaiting. Symptom: the state is still Pending. Right: await settle() first.

  5. Comparing whole SSR strings. Symptom: tests break when hydration markers change. Right: assertContains on the meaningful text or attributes.

  6. Using Dom.element after open! Zekr. Symptom: "This type constructor, Dom.element, can't be found." Right: type domElement = Dom.element before open! Zekr.

Edge cases

  • Dom.Event.typeText appends to the element's current value character by character and finally dispatches change; use Dom.Event.clear first to replace text.
  • View.onMount callbacks run after the component is in the document; when mounting into a Dom.render container they have run by the time View.mount returns. Callbacks scheduled with timers need a real await (Zekr has no fake timers).
  • Code under test that uses setTimeout (debounce) needs the test to wait at least that long (await a promise around setTimeout(_, ms + 10)), or inject the delay as a parameter.
  • To test SSR state transfer (SSRState.register/generateScript), run that suite without jsdom so SSRContext.isServer is true.
  • Dom.render containers persist until Dom.cleanup; queries scoped to container avoid matching leftovers.

SSR and hydration

  • SSR.renderToString works under jsdom; it does not use the DOM. Resources created during the render stay Pending.
  • To test hydration: set document.body (or a container) to server HTML from SSR.renderToString, then call Hydration.hydrateById(app, "container-id") and interact; the component MUST produce the same tree as the server render.

Verify

  • npm test prints a per-suite report and exits non-zero on failure (Zekr calls process.exit(1)).
  • A green run of the canonical suites above in a fresh project confirms the setup (they were run against Xote's sources: 5 sync and 2 async tests pass).
  • If DOM queries throw "document is not defined", jsdom was not installed before the code ran: check the --import flag and the setup file path.
  • /docs/guides/forms — form interaction tests (typeText, queryByDisplayValue).
  • /docs/guides/fetching-data — resource behaviour under test.
  • /docs/advanced/batching — batching rules asserted above.
  • /docs/advanced/ssr — rendering and hydration APIs.
  • /docs/learn/effects — ownership and disposal.