TestHost unstable
Runtime tests: mount a component tree on a plain-object host, drive it, and wait for it to settle.
TestHost records what it's asked to do, implements every event behaviour
h promises (only the innermost element with a handler for an event gets
it), and records onMount work instead of running it: Play.mounted
sends what the body would have. Its
Layer swaps in a test scheduler that Commands, Subscriptions, Layer builds,
the render flush and the fibers of Layers built on top of it all go
through, so settle can drain everything, and provides
MessageLog.memory, so root.log() reads back what happened.
Runtime tests are plain scoped Effects. An app's tests drive a tree on
TestHost through Play and HtmlPlay, which act as a user does and
settle on their own. Use TestHost directly to assert on what happens
between settles. One instance on its own is a Story or a Scene.
Example Counting on a TestHost
import { Effect, Schema } from "effect"import { Component, UiSchema } from "effect/ui"import { Locator, TestHost } from "effect/ui/testing"
const Msg = UiSchema.TaggedEnum({ ClickedIncrement: {} })
const Counter = Component.define({ name: "Counter", model: Schema.Number, message: Msg}).make({ init: () => 0, update: ($) => $.model + 1, view: (h, count) => h.el("button").on("click", Msg.ClickedIncrement()).children(String(count))})
const program = Effect.gen(function*() { const root = yield* TestHost.mount(Counter, {}) Locator.fire(root.get(Locator.text("0")), "click") yield* TestHost.settle return root.text()}).pipe(Effect.scoped, Effect.provide(TestHost.layer()))
console.log(await Effect.runPromise(program)) // "1"Combinators
Runs everything the test scheduler holds, and what that schedules, until nothing is left.
Details
After tasks run on the test scheduler, settle waits for one macrotask
with no further tasks. This gives resolved Promises and zero-delay timers
a chance to resume Subscriptions and Layer fibers on the host's Scheduler.
Pending Commands and fetches get up to three quiet macrotasks; a Component.lazy
load is waited for until it settles.
If no tasks have run since settle last drained the host and no Command,
fetch or load is pending, settle returns without a macrotask wait.
A fiber blocked on a Queue or TestClock does not prevent settling. Advance
TestClock to wake sleeping fibers. Commands and fetches that have not
returned remain in pending().
Fibers on the host's Scheduler share the tree's task budget: see layer.
After draining, settle undoes edits the Model refused on each tree
registered by mount.
Gotchas
Except for lazy loads, settle does not wait indefinitely for Promises or
real timers. Drive work that outlasts the macrotask grace from the test.
A tree mounted with Renderer.mount directly isn't registered: settle
runs its work, but doesn't wait for its runs and fetches, report its crash
or restore its controlled properties.
When the budget runs out, settle fails with a SettleError holding the
log's tail and what is pending. A crashed root fails it with RootCrashed,
an unhandled child failure with ChildFailed and a query problem with
ProblemsError, unless expectFailure or expectProblem took it.
Signature
declare const settle: Effect.Effect<void, SettleError | RootCrashed | ChildFailed | TestQuery.ProblemsError, TestHost>Constructors
Makes a test host. operations lists what the renderer asked of it, which
clearOperations empties. mounts lists the live mounts it recorded.
Signature
declare function makeHost(): Host<TestNode> & { readonly clearOperations: () => void; readonly commits: () => number; readonly mounts: () => readonly Array<TestMount>; readonly onCommit: (listener: () => void) => () => void; readonly operations: () => readonly Array<string>;}Mounts a component tree on the test host, for the life of the current Scope.
Details
The first render happens at once. Commands, Subscriptions, fetches and
Layer builds wait for settle. The test host shows every vocabulary, so
any root mounts.
The mount uses the host's Query.Visibility, Query.Connectivity and
problem collector even if a nearer provide overrides them. Its Clock
drains the test scheduler whenever a sleeper wakes, so TestClock.adjust
runs the awakened work without waiting for settle.
frames projects the tree after each commit for root.frames(), and
defaults to root.text().
props may be an Effect, such as Router.props(AppRoute) under
Router.memory, run once before init, as with Renderer.mount.
Signature
declare function mount<Name extends string, Props, Model, Msg, Events, R, V extends Elements, RF = never, RP = never>(component: Members<Name, Props, Model, Msg, Events, R, V, any>, props: PropsInput<Props, never, RP>, options?: { readonly fallback?: (failure: Failure<never, unknown>, h: WithTags<never, {}, V>) => Content<never, RF>; readonly frames?: (root: TestRoot<Model, Msg, Events>) => string; readonly query?: QueryOptions;}): Effect<TestRoot<Model, Msg, Events, Props>, never, Scope | TestHost | R | RF | RP>Stands in for a feature in a Play or a runtime test: it renders a <stub> element
with a data-stub attribute naming the feature, records the props it gets,
and emits what the test sends.
Signature
declare function stub<Self, Props, Events>(feature: Service<Self, Props, Events>): Stub<Self, Props, Events>Errors
ChildFailed
unstableChildren failed, and nothing handled them or took them with
expectFailure. settle fails with it.
Signature
declare class ChildFailed extends YieldableError<this> & { readonly _tag: "ChildFailed";} & Readonly<{ readonly failures: readonly Array<ChildFailure>;}> { constructor(args: { readonly failures: readonly Array<ChildFailure>; }); message: string;}RootCrashed
unstableA root mounted on the host crashed. settle fails with it.
Signature
declare class RootCrashed extends YieldableError<this> & { readonly _tag: "RootCrashed";} & Readonly<{ readonly cause: Cause<unknown>; readonly path: string;}> { constructor(args: { readonly cause: Cause<unknown>; readonly path: string; }); message: string;}SettleError
unstablesettle ran out of budget: something keeps scheduling work.
Signature
declare class SettleError extends YieldableError<this> & { readonly _tag: "SettleError";} & Readonly<{ readonly log: readonly Array<Entry>; readonly message: string; readonly pending: readonly Array<Pending>;}> { constructor(args: { readonly log: readonly Array<Entry>; readonly message: string; readonly pending: readonly Array<Pending>; });}Formatting
Formats log entries one per line, for test failures.
Signature
declare function formatLog(entries: readonly Array<Entry>): stringformatTimeline
unstableFormats log entries as a timeline: each fact on its own line, in the order they happened, with the entries that follow from it indented under it.
Details
A fact is an entry without causedBy: a message from a DOM event, a
Command's result, a Subscription, root.send or root.setProps, a query
result, a Layer build or a run ending. The entries under it are what the
tree did about it, in the order they were logged: the messages its update
sent on, the props, mounts and unmounts of its render, the runs it stopped
and the fetches its render started. See MessageLog.Base.
An entry is listed under its fact even when the flush that logged it ran
after later facts, so its number can be higher than the next fact's. An
entry whose fact isn't among entries, as when a ring buffer dropped it,
is listed as a fact, with (after #n) naming the missing one.
Signature
declare function formatTimeline(entries: readonly Array<Entry>): stringExample Printing what a click did
import { TestHost } from "effect/ui/testing"
declare const root: TestHost.TestRoot<unknown, unknown, unknown>
console.log(TestHost.formatTimeline(root.log()))// #7 /Parent Update Inc (dispatch)// #8 /Parent/Child[child] PropsChanged// #9 /Parent/Child[child] Update Read (dom click)Layers
Provides TestHost, the Renderer for it, the test scheduler and a
MessageLog.memory log.
Details
budget is how many scheduler tasks settle and a clock wake run before
they give up (100,000 by default), and logSize the size of the log's ring
buffer, unbounded by default.
flush is when a render flush runs among the scheduler's tasks: see
Flush. Without it, the config EFFECT_UI_TEST_FLUSH decides, which the
default ConfigProvider reads from the environment: queued, first,
last, or an integer for a seed. That runs a whole suite under another
policy without a change to its tests. Without either it's "queued".
The Layer owns settable Query.Visibility and Query.Connectivity, both
starting true, and collects the problems every mounted cache reports.
It also provides a Scheduler to what is built and run on top of it, such
as an app's Layers and the fibers a test forks. Their tasks join the test
scheduler's queue, so settle runs them with the tree's, and the caller's
scheduler runs them when no settle does. A backend worker shared by every
root has published what a Command handed it by the time settle returns,
and a test can still await the backend directly.
Gotchas
A problem fails the test: settle fails with a ProblemsError, and the
Layer's Scope closes with one as a defect, unless expectProblem took it.
So does an unhandled child failure, with a ChildFailed, unless
expectFailure took it.
Provide the host beneath the app's Layers, as in
Backend.layer.pipe(Layer.provideMerge(TestHost.layer())). A Layer merged
beside it, as by Layer.mergeAll, runs its fibers on the default
scheduler, and settle can return before they do.
Signature
declare function layer(options?: { readonly budget?: number; readonly flush?: Flush; readonly logSize?: number;}): Layer<Renderer | TestHost>Models
A child that failed in in, under a parent that gave it neither
onFailure nor a fallback that renders.
Signature
interface ChildFailure { readonly cause: Cause<unknown>; readonly in: FailedIn; readonly path: string;}When a tree's render flush runs among the tasks the test scheduler holds: the steps of Command, Subscription, mount and Layer fibers.
Details
"queued": in its turn, after the tasks queued before it. The default."first": before every task already queued."last": once no task is queued, the ones queued meanwhile included.{ seed }: at a place a generator seeded withseedpicks, so a run that fails is repeated by its seed.
A browser renders on its own clock, between whatever work arrives. A test that passes under one of these and fails under another has found behaviour that depends on when the render ran.
Signature
type Flush = "queued" | "first" | "last" | { readonly seed: number;}Work still in flight: a Command run, a fetch or a lazy component's load.
Signature
type Pending = PendingCommand | PendingFetch | PendingLoadA Command run still in flight: the instance that issued it, its name, and
whether it's running, queued, awaiting (its fiber exited and its
message waits, on a Command.afterRefetch wait or, under queue, behind
an earlier message of its group) or stopping (it was interrupted and its
fiber, cleanup included, hasn't exited).
Signature
interface PendingCommand { readonly _tag: "Command"; readonly name: string; readonly path: string; readonly status: string;}A fetch the cache holds: running, or held until a live patch's run
exits, with the trigger it started or will start with.
Signature
interface PendingFetch { readonly _tag: "Fetch"; readonly logKey: string; readonly path: string; readonly query: string; readonly status: "running" | "held"; readonly trigger: Trigger;}A Component.lazy module a slot waits for: the slot's path and the name
given to lazy.
Signature
interface PendingLoad { readonly _tag: "Load"; readonly name: string; readonly path: string;}A tree mounted on TestHost's scheduler, whatever host renders it: what
a test reads and drives without looking at nodes.
Details
mount hands back a TestRoot, which adds the test host's node lookups.
Ssr.ssr hands back this part only, since its client renders into a real
document.
Signature
interface Root<out Model, in Msg, out Events, in Props = never> { readonly emitted: readonly Array<Events>; readonly entry: <R extends Any>(read: R, args: Args<R>) => Entry<Success<R>, Error<R>> | undefined; readonly fetches: () => readonly Array<FetchStarted>; readonly frames: () => readonly Array<string>; readonly head: <H = Head>() => H; readonly instance: (instance: number) => ControlledInstance | undefined; readonly log: () => readonly Array<Entry>; readonly model: () => Model | undefined; readonly path: string; readonly pending: () => readonly Array<Pending>; readonly send: (message: Msg) => void; readonly session: string; readonly setProps: (props: Props) => void;}A stand-in for a feature, from stub.
Signature
interface Stub<Self, Props, Events> { readonly emit: (events: Events) => void; readonly layer: Layer<Self>; readonly props: () => readonly Array<Props>;}An element on the test host.
Details
attrs and props hold what the renderer set. To act as the user editing
a controlled property, set props directly, then fire the event. On a
tree mount made, the next settle undoes an edit the Model refused, as
a real host does.
handlers, eventOptions, owners and dispatch are read from the
tree the renderer rendered last, so an element that left it has none.
eventOptions holds the options set with the handlers. The test host has
no default actions, so it applies none of them; a Story reports
defaultPrevented.
Signature
interface TestElement extends Firable { readonly _tag: "Element"; readonly attrs: Record<string, string>; readonly children: Array<TestNode>; readonly dispatch: Dispatch | undefined; readonly eventOptions: Readonly<Record<string, View.EventOptions>>; readonly handlers: Readonly<Record<string, View.Handler<unknown, any>>>; readonly owners: Readonly<Record<string, ReadonlyArray<string>>>; parent: TestElement | undefined; readonly props: Record<string, unknown>; readonly tag: string;}A mount TestHost recorded instead of running its body, for as long as
its element lives: the instance's path, the element, and the mount the
view last rendered there.
Signature
interface TestMount extends HostMount<TestNode> { readonly answer: (result: unknown) => void;}Any node on the test host.
Signature
type TestNode = TestElement | TestTextA tree mounted on TestHost, with lookups over its nodes.
Signature
interface TestRoot<out Model, in Msg, out Events, in Props = never> extends Root<Model, Msg, Events, Props> { readonly all: (locator: Locator) => readonly Array<TestNode>; readonly container: TestElement; readonly get: (locator: Locator) => TestNode; readonly query: (locator: Locator) => TestNode | undefined; readonly text: () => string;}A text node on the test host.
Signature
interface TestText extends Firable { readonly _tag: "Text"; parent: TestElement | undefined; readonly tag?: undefined; text: string;}A tree registered with TestHost.
Signature
interface Tree { readonly container?: TestElement; readonly crashed: () => Cause<unknown> | undefined; readonly path: string; readonly pending: () => readonly Array<Pending>;}Problems
DrainExhausted
unstableA drain woken by the clock ran out of budget. What was queued stays queued,
and the next settle runs it and fails on this problem.
Signature
declare class DrainExhausted extends Readonly<{ readonly message: string;}> & { readonly _tag: "DrainExhausted";} & Pipeable { constructor(args: { readonly message: string; });}Services
The TestHost service.
Signature
declare const TestHost: Service<TestHost, TestHost>The TestHost service: the host, the test scheduler and the log.
Signature
interface TestHost { readonly budget: number; readonly busy: () => boolean; readonly connectivity: SettableSignal; readonly drain: (budget: number) => boolean; readonly drainingClock: (clock: Clock, context: Context<never>) => Clock; readonly expectFailure: (path: string) => readonly Array<ChildFailure>; readonly expectProblem: (tag: string) => readonly Array<Any>; readonly failures: () => readonly Array<ChildFailure>; readonly host: Host<TestNode> & { readonly clearOperations: () => void; readonly commits: () => number; readonly mounts: () => readonly Array<TestMount>; readonly onCommit: (listener: () => void) => () => void; readonly operations: () => readonly Array<string>; }; readonly log: Memory; readonly pending: () => readonly Array<Pending>; readonly problems: () => readonly Array<Any>; readonly ran: () => number; readonly register: (tree: Tree) => () => void; readonly report: (problem: Any) => void; readonly trees: () => ReadonlySet<Tree>; readonly visibility: SettableSignal;}Testing
expectFailure
unstableTakes every unhandled child failure at path, so it no longer fails
settle or the test, and returns them.
Details
Call it when a test fails a child on purpose and its parent gives it
neither onFailure nor a fallback that renders: the step or settle
after the failure fails with ChildFailed, and later ones pass once it's
taken. A fallback that throws is a failure in "fallback".
A root's crash is RootCrashed, not a child failure, and neither is a
failed Component.lazy load.
Gotchas
Dies when no child failed at path.
Signature
declare function expectFailure(path: string): Effect<readonly Array<ChildFailure>, never, TestHost>expectProblem
unstableTakes every reported problem with the given tag, so it no longer fails
settle or the test, and returns them.
Gotchas
Dies when no problem with that tag was reported.
Signature
declare function expectProblem<Tag extends string>(tag: Tag): Effect<readonly Array<[Extract<DrainExhausted, { readonly _tag: Tag;}> | Extract<DuplicateName, { readonly _tag: Tag;}> | Extract<IntervalThrew, { readonly _tag: Tag;}> | Extract<IntervalInvalid, { readonly _tag: Tag;}> | Extract<FetchRestarted, { readonly _tag: Tag;}> | Extract<PageRepeated, { readonly _tag: Tag;}> | Extract<DuplicateKeyInPage, { readonly _tag: Tag;}> | Extract<PatchInvalid, { readonly _tag: Tag;}> | Extract<PatchMutated, { readonly _tag: Tag;}> | Extract<UncoveredWrite, { readonly _tag: Tag;}> | Extract<InvalidateIgnored, { readonly _tag: Tag;}> | Extract<EncodeFailed, { readonly _tag: Tag;}> | Extract<HydrationMalformed, { readonly _tag: Tag;}> | Extract<HydrationDecodeFailed, { readonly _tag: Tag;}> | Extract<ReactivityMissing, { readonly _tag: Tag;}>] extends [never] ? Any : Extract<DrainExhausted, { readonly _tag: Tag;}> | Extract<DuplicateName, { readonly _tag: Tag;}> | Extract<IntervalThrew, { readonly _tag: Tag;}> | Extract<IntervalInvalid, { readonly _tag: Tag;}> | Extract<FetchRestarted, { readonly _tag: Tag;}> | Extract<PageRepeated, { readonly _tag: Tag;}> | Extract<DuplicateKeyInPage, { readonly _tag: Tag;}> | Extract<PatchInvalid, { readonly _tag: Tag;}> | Extract<PatchMutated, { readonly _tag: Tag;}> | Extract<UncoveredWrite, { readonly _tag: Tag;}> | Extract<InvalidateIgnored, { readonly _tag: Tag;}> | Extract<EncodeFailed, { readonly _tag: Tag;}> | Extract<HydrationMalformed, { readonly _tag: Tag;}> | Extract<HydrationDecodeFailed, { readonly _tag: Tag;}> | Extract<ReactivityMissing, { readonly _tag: Tag;}>>, never, TestHost>Returns the problems reported on this host that no expectProblem took.
Signature
declare const problems: Effect.Effect<ReadonlyArray<Query.Problem.Any>, never, TestHost>Sets the host's Query.Connectivity, which every mount on it reads. It
starts true. Going from false to true, while visible, refetches every
watched entry that is stale or whose interval elapsed.
Signature
declare function setOnline(online: boolean): Effect<void, never, TestHost>setVisible
unstableSets the host's Query.Visibility, which every mount on it reads. It
starts true. Going from false to true, while online, refetches every
watched entry that is stale or whose interval elapsed.
Signature
declare function setVisible(visible: boolean): Effect<void, never, TestHost>