Testing
Test signals, components, server-rendered HTML and resources with the same tools Xote uses for its own tests.
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'23const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {4 url: 'http://localhost/',5})67globalThis.window = dom.window8globalThis.document = dom.window.document9globalThis.Node = dom.window.Node10globalThis.HTMLElement = dom.window.HTMLElement11globalThis.Event = dom.window.Event12globalThis.MouseEvent = dom.window.MouseEvent13globalThis.KeyboardEvent = dom.window.KeyboardEvent14globalThis.InputEvent = dom.window.InputEvent
Then an entry file that runs your suites:
1// tests/Tests.res2Zekr.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.res2open! Zekr34let 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 None7 })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.res2@xote.component3let 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,Dommeans Zekr's DOM helpers. If you need the standardDom.elementtype in a test file, alias it before theopen: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.2Async tests use asyncTest and asyncSuite. To let a promise settle, wait one tick:
1// tests/Async_test.res2open! Zekr34let settle = () => Promise.make((resolve, _) => setTimeout(() => resolve(), 0)->ignore)56let 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.res2Zekr.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 withnode --import ./tests/setup.mjsinstead. - Leaving effects running. An effect created in a test lives until it's disposed. Use
Effect.runWithDisposerand calldispose(). - 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
| Item | Import / entry | First stable | Changed in 7.2.0 | Needs the PPX |
|---|---|---|---|---|
Signal, Computed, Effect.runWithDisposer, Signal.batch | xote | stable (all 7.x) | — | No |
View.mount, SSR.renderToString | xote, xote/ssr | 7.0.0 | — | No |
Resource (async tests) | xote | 7.2.0 (new) | — | No |
| Zekr (tested with 1.7.0) | npm zekr, ReScript dependency zekr | external | — | — |
| jsdom | npm jsdom | external | — | — |
Rules
- Install
zekrandjsdomas dev dependencies, add"zekr"to"dev-dependencies"inrescript.json, and declare the test folder as a dev source ({"dir": "tests", "subdirs": true, "type": "dev"}). - jsdom MUST be installed on
globalThis(window,document,Node,HTMLElement,Event,MouseEvent,KeyboardEvent,InputEvent) before Xote's modules evaluate. Preload the setup file withnode --import ./tests/setup.mjs …. %%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 andSSRContext.isServeristruefor the whole run. DOM rendering still works (it readsdocumentat call time), but code guarded bySSRContext.isClientdoes not run andSSRState.registerrecords values as if on the server. Use--importwhen the test depends onisClient.Zekr.runSuites(synchronous) exits the process when it reports. Async suites MUST run from a separate entry withZekr.runAsyncSuites.- Signal writes propagate synchronously: computeds read with
Signal.peekare current, effects have run, and DOM reactive leaves are updated whenSignal.set/Signal.updatereturns, and when a dispatched DOM event's handler returns. - Inside
Signal.batch, dependents are notified once, when the outermost batch returns. - An effect created in a test (outside a component) has no owner and runs until disposed. Create it with
Effect.runWithDisposerand call.dispose()before the test ends. - Module-level signals keep their values across tests in the same process. Create signals inside the test, or reset them in
~beforeEach. Dom.render(html)appends a fresh containerdivtodocument.bodyand returns{container, baseElement}. Mount components intocontainerwithView.mount. Pass~afterEach=Dom.cleanuptosuiteto remove containers between tests.- A resource settles after its promise resolves:
awaita macrotask (setTimeout(_, 0)) before asserting on its state. For deterministic ordering, return promises whose resolvers the test controls. - After
open! Zekr,Domrefers to Zekr's DOM helpers and the standardDom.element/Dom.eventtypes are hidden. Alias them before theopen(type domElement = Dom.element). - Assert on SSR output with
assertContains(substrings), not full-string equality: the HTML contains hydration markers whose exact form is an implementation detail.
API
| Name | Signature | Behaviour |
|---|---|---|
Zekr.test | (string, unit => testResult) => testCase | Synchronous test. |
Zekr.asyncTest | (string, unit => promise<testResult>, ~timeout: int=?) => asyncTestCase | Async test. |
Zekr.suite | (string, array<testCase>, ~beforeAll=?, ~afterAll=?, ~beforeEach=?, ~afterEach=?) => testSuite | Group with hooks. |
Zekr.asyncSuite | same, with promise<unit> hooks | Async group. |
Zekr.runSuites / runAsyncSuites | array<testSuite> => unit / array<asyncTestSuite> => promise<unit> | Run, report, and exit with status 0 or 1. |
assertEqual, assertTrue, assertFalse, assertContains, assertSome, assertNone, assertThrows | assertions returning testResult | Structural equality, substring, option checks. |
combineResults | array<testResult> => testResult | Several assertions in one test. |
Dom.render | string => {container: Dom.element, baseElement: Dom.element} | Fresh container in the document. |
Dom.cleanup | unit => unit | Removes containers created by render. |
Dom.Query.getByRole / getByText / getByLabelText / getByPlaceholder / getByTestId / getByDisplayValue (+ queryBy…, getAllBy…) | (Dom.element, string, …) => Dom.element | Find elements like a user; queryBy… returns option. |
Dom.Event.click / typeText / clear / check / uncheck / selectOptions / focus / blur | Dom.element => unit (plus text/values) | Dispatch realistic events (typeText fires keydown/input/keyup per character, then change). |
Dom.Assert.toHaveTextContent / toHaveAttribute / toHaveClass / toBeInTheDocument | … => testResult | DOM assertions. |
Effect.runWithDisposer | (unit => option<unit => unit>, ~name: string=?) => {dispose: unit => unit} | Effect you can stop. |
SSR.renderToString | (unit => View.node, ~options=?) => string | HTML 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.mjs2import { JSDOM } from 'jsdom'34const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', { url: 'http://localhost/' })5globalThis.window = dom.window6globalThis.document = dom.window.document7globalThis.Node = dom.window.Node8globalThis.HTMLElement = dom.window.HTMLElement9globalThis.Event = dom.window.Event10globalThis.MouseEvent = dom.window.MouseEvent11globalThis.KeyboardEvent = dom.window.KeyboardEvent12globalThis.InputEvent = dom.window.InputEvent
1// tests/Tests.res2Zekr.runSuites([Counter_test.suite])
1// tests/AsyncTests.res2Zekr.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! Zekr23let 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 + 119 None20 })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 run27 assertEqual(runs.contents, 2)28 }),29 ],30)
Component interaction — Use when: testing what a user sees and does.
1// src/Counter.res2@xote.component3let 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.res2open! Zekr34let 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! Zekr23let settle = () => Promise.make((resolve, _) => setTimeout(() => resolve(), 0)->ignore)45let 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
-
Relying on
%%rawto load jsdom first. Wrong:%%raw(import './setup.mjs')as the first line ofTests.res, run withnode tests/Tests.res.mjs. Symptom: rendering works, butSSRContext.isClientisfalse, soif SSRContext.isClient { … }branches never run in tests andSSRState.registerbehaves 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. -
Undisposed effects. Wrong:
Effect.run(() => { log->Array.push(Signal.get(name)); None })in a test. Symptom: later tests that setname(or a shared signal) trigger the old effect; counts drift between runs. Right:let e = Effect.runWithDisposer(…)ande.dispose(). -
Async suites in the sync entry. Wrong:
Zekr.runSuites([...])followed byZekr.runAsyncSuites([...])in one file. Symptom: async tests never run; the process exits after the sync report. Right: separate entry files. -
Asserting a resource immediately. Wrong:
Resource.make(…)thenassertEqual(Signal.peek(r), Ready(…))without awaiting. Symptom: the state is stillPending. Right:await settle()first. -
Comparing whole SSR strings. Symptom: tests break when hydration markers change. Right:
assertContainson the meaningful text or attributes. -
Using
Dom.elementafteropen! Zekr. Symptom: "This type constructor,Dom.element, can't be found." Right:type domElement = Dom.elementbeforeopen! Zekr.
Edge cases
Dom.Event.typeTextappends to the element's current value character by character and finally dispatcheschange; useDom.Event.clearfirst to replace text.View.onMountcallbacks run after the component is in the document; when mounting into aDom.rendercontainer they have run by the timeView.mountreturns. Callbacks scheduled with timers need a realawait(Zekr has no fake timers).- Code under test that uses
setTimeout(debounce) needs the test to wait at least that long (awaita promise aroundsetTimeout(_, ms + 10)), or inject the delay as a parameter. - To test SSR state transfer (
SSRState.register/generateScript), run that suite without jsdom soSSRContext.isServeristrue. Dom.rendercontainers persist untilDom.cleanup; queries scoped tocontaineravoid matching leftovers.
SSR and hydration
SSR.renderToStringworks under jsdom; it does not use the DOM. Resources created during the render stayPending.- To test hydration: set
document.body(or a container) to server HTML fromSSR.renderToString, then callHydration.hydrateById(app, "container-id")and interact; the component MUST produce the same tree as the server render.
Verify
npm testprints a per-suite report and exits non-zero on failure (Zekr callsprocess.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
--importflag and the setup file path.
Related
/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.