@shivaedev/test-story 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/README.md +134 -77
- package/dist/client/react.d.ts +28 -0
- package/dist/client/react.d.ts.map +1 -0
- package/dist/client/react.js +108 -0
- package/dist/client/react.js.map +1 -0
- package/dist/server/domEnvironment.config.d.ts.map +1 -1
- package/dist/server/domEnvironment.config.js +7 -1
- package/dist/server/domEnvironment.config.js.map +1 -1
- package/dist/server/domFetch.d.ts +6 -1
- package/dist/server/domFetch.d.ts.map +1 -1
- package/dist/server/domFetch.js +3 -3
- package/dist/server/domFetch.js.map +1 -1
- package/dist/server/fakeHttpService.d.ts +0 -2
- package/dist/server/fakeHttpService.d.ts.map +1 -1
- package/dist/server/fakeHttpService.js +1 -3
- package/dist/server/fakeHttpService.js.map +1 -1
- package/dist/server/forwardingProxy.d.ts +2 -0
- package/dist/server/forwardingProxy.d.ts.map +1 -1
- package/dist/server/forwardingProxy.js +27 -4
- package/dist/server/forwardingProxy.js.map +1 -1
- package/dist/server/internal/adapters/memberFetch.d.ts +3 -0
- package/dist/server/internal/adapters/memberFetch.d.ts.map +1 -0
- package/dist/server/internal/adapters/memberFetch.js +68 -0
- package/dist/server/internal/adapters/memberFetch.js.map +1 -0
- package/dist/server/internal/compose.d.ts.map +1 -1
- package/dist/server/internal/compose.js +1 -0
- package/dist/server/internal/compose.js.map +1 -1
- package/dist/server/internal/domDocument.d.ts +4 -0
- package/dist/server/internal/domDocument.d.ts.map +1 -0
- package/dist/server/internal/domDocument.js +13 -0
- package/dist/server/internal/domDocument.js.map +1 -0
- package/dist/server/internal/fakeHttpControls.d.ts +2 -2
- package/dist/server/internal/fakeHttpControls.d.ts.map +1 -1
- package/dist/server/internal/fakeHttpControls.js +14 -6
- package/dist/server/internal/fakeHttpControls.js.map +1 -1
- package/dist/server/internal/fakeHttpReceive.d.ts.map +1 -1
- package/dist/server/internal/fakeHttpReceive.js +2 -7
- package/dist/server/internal/fakeHttpReceive.js.map +1 -1
- package/dist/server/internal/fakeHttpScripts.d.ts +1 -1
- package/dist/server/internal/fakeHttpScripts.d.ts.map +1 -1
- package/dist/server/internal/fakeHttpScripts.js +2 -4
- package/dist/server/internal/fakeHttpScripts.js.map +1 -1
- package/dist/server/internal/hookInference.d.ts +1 -12
- package/dist/server/internal/hookInference.d.ts.map +1 -1
- package/dist/server/internal/installOutbound.d.ts.map +1 -1
- package/dist/server/internal/installOutbound.js +1 -1
- package/dist/server/internal/installOutbound.js.map +1 -1
- package/dist/server/internal/seed.d.ts +1 -0
- package/dist/server/internal/seed.d.ts.map +1 -1
- package/dist/server/internal/seed.js.map +1 -1
- package/dist/server/internal/storyIt.d.ts.map +1 -1
- package/dist/server/internal/storyIt.js +4 -2
- package/dist/server/internal/storyIt.js.map +1 -1
- package/dist/server/memberScreens.d.ts +20 -0
- package/dist/server/memberScreens.d.ts.map +1 -0
- package/dist/server/memberScreens.js +40 -0
- package/dist/server/memberScreens.js.map +1 -0
- package/dist/server/routeOutbound.d.ts +3 -1
- package/dist/server/routeOutbound.d.ts.map +1 -1
- package/dist/server/routeOutbound.js +3 -2
- package/dist/server/routeOutbound.js.map +1 -1
- package/dist/server/screenDriver.d.ts +3 -2
- package/dist/server/screenDriver.d.ts.map +1 -1
- package/dist/server/screenDriver.js +14 -2
- package/dist/server/screenDriver.js.map +1 -1
- package/dist/server/seedCookies.d.ts +2 -1
- package/dist/server/seedCookies.d.ts.map +1 -1
- package/dist/server/seedCookies.js +4 -4
- package/dist/server/seedCookies.js.map +1 -1
- package/dist/server/storyKit.d.ts +2 -4
- package/dist/server/storyKit.d.ts.map +1 -1
- package/dist/server/storyKit.js.map +1 -1
- package/package.json +31 -13
- package/src/client/react.ts +142 -0
- package/src/server/domEnvironment.config.ts +7 -1
- package/src/server/domFetch.ts +6 -3
- package/src/server/fakeHttpService.ts +1 -5
- package/src/server/forwardingProxy.ts +47 -24
- package/src/server/internal/adapters/memberFetch.ts +67 -0
- package/src/server/internal/compose.ts +1 -0
- package/src/server/internal/domDocument.ts +15 -0
- package/src/server/internal/fakeHttpControls.ts +14 -9
- package/src/server/internal/fakeHttpReceive.ts +2 -6
- package/src/server/internal/fakeHttpScripts.ts +2 -4
- package/src/server/internal/hookInference.ts +1 -19
- package/src/server/internal/installOutbound.ts +1 -1
- package/src/server/internal/seed.ts +1 -0
- package/src/server/internal/storyIt.ts +4 -2
- package/src/server/memberScreens.ts +61 -0
- package/src/server/routeOutbound.ts +3 -2
- package/src/server/screenDriver.ts +17 -4
- package/src/server/seedCookies.ts +4 -4
- package/src/server/storyKit.ts +2 -15
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,53 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.25.0 - 2026-10-30
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Export every engine module through the package's existing `.ts` wildcard, including modules under `internal/` in `test` and `vitest-rerun` and `server/internal/` in `test-story` and `test-sql`, so downstream kits can reuse them directly. Importing the rerun worker leaves test execution to its direct launch.
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- Generated applications import React test helpers from their existing `@shivaedev/test-story` development dependency.
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- Every story in the DOM environment starts with no cookies, `localStorage` or `sessionStorage`, so a story no longer passes or fails because of what an earlier story in the same file stored.
|
|
16
|
+
|
|
17
|
+
### Breaking
|
|
18
|
+
|
|
19
|
+
- Remove the legacy engine-first `storyKit` overload. Replace `storyKit<Engine, "ready", Verbs>({ ... })` with `storyKit({ ... })`; annotate the return type of `create` when an explicit engine shape is needed. Stages, verbs and services are inferred from the definition.
|
|
20
|
+
- Remove `fakeHttpService.failOnce` and `replyOnce`. Replace either `api.failOnce(route, reply, scope)` or `api.replyOnce(route, reply, scope)` with `api.scriptFault(route, { kind: "status", reply }, scope)`. The default still consumes only the next authorized matching request. The result now contains a `lift` effect, and narration uses the existing scripted-fault wording.
|
|
21
|
+
- Move the React test helpers to `@shivaedev/test-story/client/react.ts`. Replace imports from `@shivaedev/react/client/testing.ts` with this path for `render`, `eventually`, `captureReactWarnings`, `expectNoReactWarnings` and their types. Add `@shivaedev/test-story` as a development dependency and install its React helpers' optional peers `react`, `react-dom` and `@effect/atom-react` when using them. React no longer brings `@shivaedev/test` into applications as a runtime dependency.
|
|
22
|
+
- Kits declaring `outbound` and direct `routeOutbound(routes)` scopes now refuse unrouted external Node fetch requests and fail at scope close, even when application code catches the fetch error. Add hostnames to the outbound map, or explicitly opt into network access with `outboundPassthrough: true` on the kit or `{ passthrough: true }` as the second argument to `routeOutbound`. Loopback requests remain allowed; the DOM environment still refuses unrouted external hosts.
|
|
23
|
+
- Thrown fake HTTP handlers now close the connection and fail the story at scope close with the request and a description of the thrown value. To simulate an upstream error, return an error status or script an HTTP fault instead of throwing.
|
|
24
|
+
|
|
25
|
+
## 0.24.0 - 2026-10-30
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- Scope screen-driver verbs and readouts with `within(container)`, and mount named member screens with independent cookie sessions, atom registries and scoped roots through `memberScreens`.
|
|
30
|
+
- Create password-credential test users with Identity's `passwordUser` helper for real email sign-in stories.
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- Work Board file edits refresh authorized contract queries over Platform's shared WebSocket, including the Claude plugin's overview. Unrelated document reads retain their values.
|
|
35
|
+
- Forwarding proxy fixtures can disconnect and resume real client traffic at the same address.
|
|
36
|
+
- Automatic contract live connections expose a `paused` atom; resuming reconciles their mounted queries. Bindings can supply a `resumeWindow` for embedded browser lifecycle events.
|
|
37
|
+
- Live status notifications use the registry's asynchronous scheduler, so mounting a query during React rendering does not update another component.
|
|
38
|
+
- Require Effect 4.0.6 and align the Effect companion package peers and generated starter catalog to the same exact release. Install the 4.0.6 Effect stack together.
|
|
39
|
+
|
|
40
|
+
### Fixed
|
|
41
|
+
|
|
42
|
+
- Register hosted RPC cache-control handling through Effect 4.0.6's request-scoped pre-response API so responses keep `private, no-store`.
|
|
43
|
+
- Accept native RPC's `application/x-ndjson` media type while preserving `application/ndjson` callers at the transport guard.
|
|
44
|
+
- Keep subscriptions open after their HTTP request body completes; closing the socket still cancels them.
|
|
45
|
+
|
|
46
|
+
### Breaking
|
|
47
|
+
|
|
48
|
+
- Work Board removes its `subscribe` RPC. Consumers bind its contract queries with Platform's default WebSocket client instead of consuming Board-specific change hints.
|
|
49
|
+
- `WorkspaceConfig.indexing` supplies a progress snapshot Effect. Replace indexing Stream overrides with an Effect that reads current progress.
|
|
50
|
+
|
|
3
51
|
## 0.23.0 - 2026-10-29
|
|
4
52
|
|
|
5
53
|
### Added
|
package/README.md
CHANGED
|
@@ -7,14 +7,16 @@ Tests that read like short English stories and run the real engine. A spec names
|
|
|
7
7
|
When agents write most of the code, test files grow into hundreds of lines nobody reads. Each test rebuilds its setup by hand, mocks whatever was too much work to build, and hides what it actually checks. A story test holds only what is specific to it:
|
|
8
8
|
|
|
9
9
|
```ts
|
|
10
|
-
bakery.it("steps until the
|
|
10
|
+
bakery.it("steps the bakery one minute at a time until the dough runs out", [ovenIsLit(), hasDough(3)], function* ({ oven }) {
|
|
11
|
+
expect(oven.minutes()).toBe(0);
|
|
12
|
+
|
|
11
13
|
yield* oven.bakesEverything();
|
|
12
|
-
|
|
14
|
+
|
|
13
15
|
expect(oven.minutes()).toBe(3);
|
|
14
16
|
});
|
|
15
17
|
```
|
|
16
18
|
|
|
17
|
-
That is a whole test. `bakery.it` comes from the bakery's story kit. The list holds its traits, `ovenIsLit()` and `hasDough(3)`, which are written once and shared by every spec. `oven.bakesEverything()` performs the baking action until the dough is gone
|
|
19
|
+
That is a whole test. `bakery.it` comes from the bakery's story kit. The list holds its traits, `ovenIsLit()` and `hasDough(3)`, which are written once and shared by every spec. `oven.bakesEverything()` performs the baking action until the dough is gone, and `oven.minutes()` reads how long the oven has baked, before and after it. The spec states each expectation. Every story runs the whole engine, so each test also checks the parts its author never thought to mock, and because a spec reads as English, a sloppy test stands out in review.
|
|
18
20
|
|
|
19
21
|
When a story fails, it prints itself. One of this package's own failing stories expects 2 loaves from one ball of dough, and the test fails with this message:
|
|
20
22
|
|
|
@@ -43,7 +45,9 @@ The first line is the assertion's own message. The box under it tells a reader w
|
|
|
43
45
|
|
|
44
46
|
## Using it
|
|
45
47
|
|
|
46
|
-
|
|
48
|
+
Every source module is available through its `.ts` subpath, including modules under `server/internal/`. Kit authors choose which engine pieces to depend on.
|
|
49
|
+
|
|
50
|
+
Before writing or reviewing stories, follow the [story-testing skill](https://github.com/ShivaeDev/platform/blob/main/packages/skills/skills/story-testing/SKILL.md), shipped by `@shivaedev/skills`. It owns the rules for how a story reads, observable evidence, boundary-driven setup, verbs and readouts, assertions, jobs, framework gaps, faked preconditions, database isolation and focused runs. The examples below explain this package's API; framework fixtures exercise this package's responsibilities, rather than prescribe application scenarios.
|
|
47
51
|
|
|
48
52
|
### How to think about it
|
|
49
53
|
|
|
@@ -130,6 +134,7 @@ This is the bakery kit this package tests itself with. `emptyBakery`, `stillWait
|
|
|
130
134
|
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
131
135
|
| `name` | What the engine is called in failures, "the bakery", and the kit's genre, "Bakery Story". |
|
|
132
136
|
| `outbound` | Optional. A map of exact hostnames to fake server origins for Node fetch and the DOM environment's document requests. |
|
|
137
|
+
| `outboundPassthrough` | Optional. Set to `true` to let unrouted Node fetch requests reach the network. The DOM environment still refuses external hosts without a route. |
|
|
133
138
|
| `around(effect)` | Optional. Wraps creation, staged seeding and the body; worker Layer acquisition remains outside it. It may require the worker services and per-test Scope. |
|
|
134
139
|
| `clock` | Optional. `"test"` by default, `"live"` for real time, or a UTC `DateTime` to start TestClock at that instant. A story’s `options.clock` takes precedence. |
|
|
135
140
|
| `create()` | A fresh engine. Every story starts from a new one. |
|
|
@@ -158,26 +163,31 @@ export default defineConfig({
|
|
|
158
163
|
Compose kits when one story crosses features that already have their own engines, traits and verbs. Keep each feature kit independent; an integration kit imports the kits and their public trait factories, so neither feature needs to import the other's internals.
|
|
159
164
|
|
|
160
165
|
```ts
|
|
161
|
-
import { expect } from "vitest";
|
|
162
166
|
import { storyKit } from "@shivaedev/test-story/server/storyKit.ts";
|
|
163
|
-
import { bakery
|
|
164
|
-
import { mill
|
|
167
|
+
import { bakery } from "./bakery.ts";
|
|
168
|
+
import { mill } from "./mill.ts";
|
|
165
169
|
|
|
166
|
-
export const village = storyKit({
|
|
167
|
-
|
|
168
|
-
|
|
170
|
+
export const village = storyKit({ extends: [mill, bakery], name: "village" });
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import { expect } from "vitest";
|
|
175
|
+
import { hasDough, ovenIsLit } from "#test/bakery.ts";
|
|
176
|
+
import { village } from "#test/village.ts";
|
|
177
|
+
import { sailsAreTurning } from "#test/mill.ts";
|
|
178
|
+
|
|
179
|
+
village.it("runs the mill's traits when the village joins the mill and the bakery", [sailsAreTurning()], ({ sails }) => {
|
|
180
|
+
expect(sails()).toBe("turning");
|
|
169
181
|
});
|
|
170
182
|
|
|
171
|
-
village.it("
|
|
172
|
-
miller.grinds(3);
|
|
183
|
+
village.it("keeps the bakery's stepped verbs when the village joins the mill and the bakery", [ovenIsLit(), hasDough(2)], function* ({ oven }) {
|
|
173
184
|
yield* oven.bakesEverything();
|
|
174
|
-
|
|
175
|
-
expect(story.engine.sails).toBe("turning");
|
|
185
|
+
|
|
176
186
|
expect(oven.loaves()).toBe(2);
|
|
177
187
|
});
|
|
178
188
|
```
|
|
179
189
|
|
|
180
|
-
`extends` takes one or more kits. The composed engine includes each kit's engine fields, the body receives all their verbs, and traits from either kit work directly. Types for engines, stages, verbs and layer services remain inferred. A composed kit can itself appear in `extends`.
|
|
190
|
+
The kit lives in `test-support/village.ts`, and the specs import it with the mill's and the bakery's traits. `extends` takes one or more kits. The composed engine includes each kit's engine fields, the body receives all their verbs, and traits from either kit work directly. Types for engines, stages, verbs and layer services remain inferred. A composed kit can itself appear in `extends`.
|
|
181
191
|
|
|
182
192
|
Creation runs in dependency order, left to right, before any traits. Stages and their `after` hooks then run in that same order, regardless of the order traits appear in the spec. All creation, traits, hooks and the body share one per-test Scope, whose finalizers release resources in reverse acquisition order, including after a failed story. Feature verbs retain their own `runUntil` hooks, so the bakery's waiting verb still steps the bakery. Use each feature's waiting verbs when driving a composed story.
|
|
183
193
|
|
|
@@ -194,9 +204,9 @@ const app = storyKit({
|
|
|
194
204
|
});
|
|
195
205
|
```
|
|
196
206
|
|
|
197
|
-
`appDefinition` holds the application's kit hooks, and `fakeUrl` is the listening fake server's HTTP or HTTPS origin, such as `http://127.0.0.1:4321`. The map matches exact URL hostnames, across ports. It replaces the destination origin while keeping the request's path, query, method, headers and body. For example, a POST to `https://github.com/login/oauth/access_token` reaches the fake's `/login/oauth/access_token`.
|
|
207
|
+
`appDefinition` holds the application's kit hooks, and `fakeUrl` is the listening fake server's HTTP or HTTPS origin, such as `http://127.0.0.1:4321`. The map matches exact URL hostnames, across ports. It replaces the destination origin while keeping the request's path, query, method, headers and body. For example, a POST to `https://github.com/login/oauth/access_token` reaches the fake's `/login/oauth/access_token`. When a kit declares `outbound`, only loopback hosts (`localhost`, IPv4 loopback addresses and `[::1]`) may pass through without a route; every other hostname must have an `outbound` fake. Node kits can opt into network access for unrouted hosts with `outboundPassthrough: true`. Composed kits inherit that opt-in from their constituent kits. The DOM environment always refuses unrouted external hosts. A refused request fails the story and names its hostname, even when application code catches the fetch error.
|
|
198
208
|
|
|
199
|
-
`routeOutbound(routes)` from `@shivaedev/test-story/server/routeOutbound.ts` installs the same routing in the current Effect Scope. Acquire a `fakeHttpService` in `create`, then yield `routeOutbound({ "api.example.com": api.url })` so the fake listener and its routing belong to that story.
|
|
209
|
+
`routeOutbound(routes)` from `@shivaedev/test-story/server/routeOutbound.ts` installs the same routing in the current Effect Scope. Acquire a `fakeHttpService` in `create`, then yield `routeOutbound({ "api.example.com": api.url })` so the fake listener and its routing belong to that story. Pass `{ passthrough: true }` as its second argument to allow unrouted Node fetch requests.
|
|
200
210
|
|
|
201
211
|
Routing uses the global dispatcher that Node's built-in `fetch` already uses. The kit's `outbound` option installs routing before `around`, creation, traits and the body, stays active during scoped cleanup, and restores the previous dispatcher after each story, including a failing story. Stories within one worker must run one at a time because that dispatcher is shared; parallelism belongs between workers or inside one story. The DOM environment uses the same routing for host-side Node fetch and document requests, including redirect destinations. It refuses external hosts even when the kit omits `outbound`.
|
|
202
212
|
|
|
@@ -209,11 +219,22 @@ This lets an application's story assert that a request starts its own trace: a r
|
|
|
209
219
|
A kit can collect spans with a native in-memory tracer, or start a fake OTLP receiver and point the application's exporter at it. Expose collection, exporter flush and any bounded wait as separate verbs. Assert only after the request span has ended. This small in-memory kit uses Effect's Web Request handler as its host:
|
|
210
220
|
|
|
211
221
|
```ts
|
|
212
|
-
import { Effect, Tracer } from "effect";
|
|
222
|
+
import { Effect, Option, Tracer } from "effect";
|
|
213
223
|
import { HttpEffect, HttpServerResponse } from "effect/http";
|
|
214
224
|
import { expect } from "vitest";
|
|
215
225
|
import { storyKit } from "@shivaedev/test-story/server/storyKit.ts";
|
|
216
226
|
|
|
227
|
+
function describeSpan(span: Tracer.NativeSpan) {
|
|
228
|
+
const status = span.status._tag === "Ended" ? "ended" : "still open";
|
|
229
|
+
if (Option.isNone(span.parent)) {
|
|
230
|
+
return `a root span, ${status}`;
|
|
231
|
+
}
|
|
232
|
+
const parent = span.parent.value;
|
|
233
|
+
return parent._tag === "ExternalSpan"
|
|
234
|
+
? `under external span ${parent.spanId} in trace ${parent.traceId}, ${status}`
|
|
235
|
+
: `under "${parent.name}", ${status}`;
|
|
236
|
+
}
|
|
237
|
+
|
|
217
238
|
const app = storyKit({
|
|
218
239
|
around: (effect) => effect.pipe(Effect.withSpan("story")),
|
|
219
240
|
*create() {
|
|
@@ -231,38 +252,30 @@ const app = storyKit({
|
|
|
231
252
|
},
|
|
232
253
|
name: "traced application",
|
|
233
254
|
stages: ["ready"],
|
|
234
|
-
verbs: ({ handler, spans }) => ({
|
|
235
|
-
|
|
255
|
+
verbs: ({ handler, spans }, story) => ({
|
|
256
|
+
sendsRequest: (headers: HeadersInit = {}) =>
|
|
236
257
|
Effect.promise(async () => {
|
|
237
|
-
|
|
238
|
-
|
|
258
|
+
story.tell("a caller sends a request");
|
|
259
|
+
await (await handler(new Request("http://app.test/", { headers }))).text();
|
|
239
260
|
}),
|
|
240
|
-
|
|
241
|
-
const span = spans.filter((span) => span.kind === "server").at(-1);
|
|
242
|
-
if (span === undefined) throw new Error("The request exported no server span");
|
|
243
|
-
return span;
|
|
244
|
-
},
|
|
261
|
+
serverSpans: () => Effect.sync(() => spans.filter((span) => span.kind === "server").map(describeSpan)),
|
|
245
262
|
}),
|
|
246
263
|
});
|
|
247
264
|
|
|
248
|
-
app.it("
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
expect(span.parent._tag).toBe("None");
|
|
253
|
-
expect(span.traceId).not.toBe(storySpan.traceId);
|
|
254
|
-
expect(span.status._tag).toBe("Ended");
|
|
265
|
+
app.it("starts each request in a root span of its own", [], function* ({ sendsRequest, serverSpans }) {
|
|
266
|
+
yield* sendsRequest();
|
|
267
|
+
|
|
268
|
+
expect(yield* serverSpans()).toEqual(["a root span, ended"]);
|
|
255
269
|
});
|
|
256
270
|
|
|
257
|
-
app.it("a request
|
|
258
|
-
yield*
|
|
259
|
-
|
|
260
|
-
expect(
|
|
261
|
-
expect(span.parent).toMatchObject({ value: { spanId: "1234567890abcdef" } });
|
|
271
|
+
app.it("continues the trace context a request's headers carry", [], function* ({ sendsRequest, serverSpans }) {
|
|
272
|
+
yield* sendsRequest({ traceparent: "00-1234567890abcdef1234567890abcdef-1234567890abcdef-01" });
|
|
273
|
+
|
|
274
|
+
expect(yield* serverSpans()).toEqual(["under external span 1234567890abcdef in trace 1234567890abcdef1234567890abcdef, ended"]);
|
|
262
275
|
});
|
|
263
276
|
```
|
|
264
277
|
|
|
265
|
-
Detachment only removes the incoming parent: spans that application startup explicitly creates still follow native Effect semantics.
|
|
278
|
+
`describeSpan` turns each span into words once in the kit, so the specs compare sentences instead of reading span fields and tags. Detachment only removes the incoming parent: spans that application startup explicitly creates still follow native Effect semantics.
|
|
266
279
|
|
|
267
280
|
#### Forwarding requests to a host
|
|
268
281
|
|
|
@@ -291,15 +304,18 @@ Set `localAddress` to choose the source socket address of the proxy's connection
|
|
|
291
304
|
Use `otlpReceiver` from `@shivaedev/test-story/server/otlpReceiver.ts` in a kit's scoped `create` hook. It listens on an allocated loopback port and closes with the story scope. Point the application's real exporter at `${receiver.url}/v1/traces`, then flush the exporter before reading:
|
|
292
305
|
|
|
293
306
|
```ts
|
|
294
|
-
app.it("exports the work span", [], function* ({ runWork, disposeRuntime,
|
|
307
|
+
app.it("exports the work span without the planted secret", [], function* ({ runWork, disposeRuntime, exportedSpanNames, exportsContaining }) {
|
|
295
308
|
yield* runWork();
|
|
296
309
|
yield* disposeRuntime();
|
|
297
|
-
|
|
298
|
-
|
|
310
|
+
|
|
311
|
+
yield* outcomes({
|
|
312
|
+
"exported spans": [exportedSpanNames(), ["CountWords"]],
|
|
313
|
+
"exports with the planted secret": [exportsContaining("planted-secret"), 0],
|
|
314
|
+
});
|
|
299
315
|
});
|
|
300
316
|
```
|
|
301
317
|
|
|
302
|
-
Here `app` is the application's kit. Its `create` acquires the receiver and the real exporter pointed at that receiver, `runWork` performs the traced operation, `disposeRuntime` disposes the exporter's runtime and flushes pending spans, and `
|
|
318
|
+
Here `app` is the application's kit. Its `create` acquires the receiver and the real exporter pointed at that receiver, `runWork` performs the traced operation, `disposeRuntime` disposes the exporter's runtime and flushes pending spans, and `exportedSpanNames` and `exportsContaining` are Effect readouts over the receiver's `spans` and `requests`. Each action is visible in the spec. The receiver accepts OTLP/HTTP JSON and protobuf. `spans` flattens all exports into decoded trace and span IDs, parent span IDs, names, numeric OTLP kinds and status codes, attributes, events and links. Attributes retain OTLP key/value objects, including lossless decimal strings for integers; each span also has `resourceAttributes`. `requests` retains every request's unmodified `body` Buffer, parsed `headers`, original `rawHeaders` pairs and `path`. Search all body bytes when checking that a secret was not exported. Optional `path`, `status` (a number or attempt callback) and `answer` configure collector responses for failure stories.
|
|
303
319
|
|
|
304
320
|
For timeout stories, return `undefined` from the `status` callback to accept an export without sending response headers. Set `answer: null` to send headers without completing the response body.
|
|
305
321
|
|
|
@@ -321,11 +337,13 @@ const api = yield* fakeHttpService({
|
|
|
321
337
|
|
|
322
338
|
Point the application's real HTTP client at `api.url`, or use the kit's `outbound` map to route its external hostname there. A service-wide `guard` returns a boolean; a missing or wrong credential gets 401 before holds or scripted replies are consumed. Each route can also declare a `guard(request)`; both guards must accept the request before holds, arrival scripts or faults run. A route's guard applies only to that route, so an installation token check can sit beside public routes. Omit the guard for a public fake. Unmatched paths and methods get 404.
|
|
323
339
|
|
|
340
|
+
If a fake handler throws, the service records the failure and closes the connection. Scope close fails the story with the request and the thrown value, even if the application handles the connection error. Return an error `status` or script a fault to simulate an upstream failure.
|
|
341
|
+
|
|
324
342
|
In `verbs`, bind `api.narrate(story.tell)` to tell received requests, replies, rejections and hold controls through the story. An optional `tell` callback can also be supplied at acquisition. The service keeps request headers and bytes in `api.requests`. Each entry has a `status`: the numeric status of a completed response, `"pending"` while waiting (including a stalled body), or `"unanswered"` when the connection closes without completing a response. Dropped connections, resets after headers and clients that hang up are unanswered. Statuses include guard rejections, unmatched routes and replies replaced by faults. Readouts can format entries as `GET /repos/o/r/actions/runs/7/artifacts 500`. Narration of normal requests includes only method, path and status.
|
|
325
343
|
|
|
326
344
|
```ts
|
|
327
345
|
api.narrate(story.tell);
|
|
328
|
-
yield* api.
|
|
346
|
+
yield* api.scriptFault("user", { kind: "status", reply: { status: 502, body: { error: "try again" } } });
|
|
329
347
|
const paused = yield* api.hold("user");
|
|
330
348
|
const pending = yield* Effect.forkChild(application.loadUser("alice"));
|
|
331
349
|
yield* paused.waiting;
|
|
@@ -333,14 +351,17 @@ yield* paused.release;
|
|
|
333
351
|
const user = yield* Fiber.join(pending);
|
|
334
352
|
```
|
|
335
353
|
|
|
336
|
-
`application.loadUser` is the application's real client call. `
|
|
354
|
+
`application.loadUser` is the application's real client call. `scriptFault` affects the next authorized matching request to that named route, then the route answers normally. `hold` pauses that route until `release`; `waiting` completes when a request reaches the hold, so a story needs no polling to know when to release it. Other routes still answer. Use a live-clock kit for HTTP stories that need real-time waits; a TestClock kit can still drive the real HTTP client while controlling the fake’s reply time.
|
|
337
355
|
|
|
338
|
-
Use the controls through kit verbs after acquiring the service. `
|
|
356
|
+
Use the controls through kit verbs after acquiring the service. `scriptFault(route, { kind: "status", reply })` scripts the next authorized reply, including raw bytes or `chunks`, a synchronous or asynchronous iterable of strings and byte arrays. Set `headers["content-type"]` to the story's media type; the default is JSON. Chunks are written in iteration order as they become available, so an async iterable can wait between pieces.
|
|
339
357
|
|
|
340
358
|
```ts
|
|
341
|
-
yield* api.
|
|
342
|
-
|
|
343
|
-
|
|
359
|
+
yield* api.scriptFault("download", {
|
|
360
|
+
kind: "status",
|
|
361
|
+
reply: {
|
|
362
|
+
body: Uint8Array.from([0, 255, 128]),
|
|
363
|
+
headers: { "content-type": "application/octet-stream" },
|
|
364
|
+
},
|
|
344
365
|
});
|
|
345
366
|
const stalled = yield* api.stall("download");
|
|
346
367
|
const pending = yield* Effect.forkChild(application.download());
|
|
@@ -351,13 +372,13 @@ const bytes = yield* Fiber.join(pending);
|
|
|
351
372
|
|
|
352
373
|
`stall(route)` sends the reply's status and headers, then pauses its body. Its `waiting` effect completes at that pause. Its `release` lets the body continue; a client that gives up also stops waiting on the server. Like a hold, a stall remains installed for matching requests until released. Holds pause before headers. `releaseOnArrival(heldRoute, arrivingRoute, scope?)` releases the current hold when an authorized request reaches the named route; script it before that arrival. Rejected requests do not trigger release.
|
|
353
374
|
|
|
354
|
-
`fault(route, fault)` acts on an arrived request in the required phase. `{ kind: "status", reply: { status: 503, body: { error: "unavailable" } } }` replaces a held reply before headers. `{ kind: "drop" }` drops a connection before headers. `{ kind: "reset" }` terminates a reply after headers, including after body chunks have arrived. Wait for the hold, stall or client observation before injecting the fault. A fault fails with guidance when no request is in the required phase; it does not queue a failure for a future call. `
|
|
375
|
+
`fault(route, fault)` acts on an arrived request in the required phase. `{ kind: "status", reply: { status: 503, body: { error: "unavailable" } } }` replaces a held reply before headers. `{ kind: "drop" }` drops a connection before headers. `{ kind: "reset" }` terminates a reply after headers, including after body chunks have arrived. Wait for the hold, stall or client observation before injecting the fault. A fault fails with guidance when no request is in the required phase; it does not queue a failure for a future call. Use `scriptFault` to queue a reply for a future call.
|
|
355
376
|
|
|
356
|
-
`hold(route, scope)`, `stall(route, scope)`, `fault(route, fault, scope)`, `
|
|
377
|
+
`hold(route, scope)`, `stall(route, scope)`, `fault(route, fault, scope)`, `scriptFault(route, fault, options)` accept an optional `{ params: { number: "7" } }`. Every supplied parameter must equal the decoded request parameter. Other resources on the same named route answer normally and do not consume the scoped reply. Scoped holds and stalls return `waiting` and `release`. `hold(route, { once: true, params: { number: "7" } })` holds only the first matching request; later matching requests answer while it remains held. Omit `params` to hold only the first request across the route. Omit `once` to keep holding every matching request until release. Pass the same parameter scope as the third argument to `releaseOnArrival` to release that hold.
|
|
357
378
|
|
|
358
379
|
Use `scriptFault(route, fault, options)` to install a fault for future authorized matching requests. It returns a control with a narrated `lift` effect. The default strikes once before the route's reply runs; `{ repeat: true }` keeps it installed until lifted. Status faults can repeat too.
|
|
359
380
|
|
|
360
|
-
A status fault’s `reply
|
|
381
|
+
A status fault’s `reply` can be a fixed `FakeHttpReply` or a function `(request, now) => FakeHttpReply`. The fake evaluates the function when it answers, using the request being answered (including a held request for `fault`) and milliseconds from the Effect `Clock` captured when the service was created. A repeating fault rebuilds its reply for every request. TestClock stories therefore get deterministic refusal times:
|
|
361
382
|
|
|
362
383
|
```ts
|
|
363
384
|
yield* api.scriptFault("user", {
|
|
@@ -464,7 +485,7 @@ bakery.it("tells each step into the story", [ovenIsLit()], function* ({ baker, o
|
|
|
464
485
|
});
|
|
465
486
|
```
|
|
466
487
|
|
|
467
|
-
`kit.it(name, traits, body, options)` declares one Vitest test, named after the kit's genre: `Bakery Story: tells each step into the story`. It starts a fresh engine, seeds the traits stage by stage and runs the body with the kit's verbs and the `story`: its `engine`, `lines`, `tell(line)` and `runUntil`. The body's second argument is Vitest's test context. A body that yields Effects, such as a verb that runs the engine, is a generator, and one that yields nothing is a plain function. A test that only checks that its traits refuse may leave the body out. `options` is a timeout in milliseconds or Vitest's test options, whose own `tags` join the genre tag when the config declares it. `it.fails`, `it.only`, `it.skip`, `it.runIf(condition)` and `it.skipIf(condition)` work as they do in Vitest.
|
|
488
|
+
`kit.it(name, traits, body, options)` declares one Vitest test, named after the kit's genre: `Bakery Story: tells each step into the story`. It starts a fresh engine, seeds the traits stage by stage and runs the body with the kit's verbs and the `story`: its `engine`, `lines`, `tell(line)` and `runUntil`. A spec reads the engine through the kit's readouts rather than `story.engine`, so each check names what it observes. The body's second argument is Vitest's test context. A body that yields Effects, such as a verb that runs the engine, is a generator, and one that yields nothing is a plain function. A test that only checks that its traits refuse may leave the body out. `options` is a timeout in milliseconds or Vitest's test options, whose own `tags` join the genre tag when the config declares it. `it.fails`, `it.only`, `it.skip`, `it.runIf(condition)` and `it.skipIf(condition)` work as they do in Vitest.
|
|
468
489
|
|
|
469
490
|
A spec starts a story, acts through verbs and checks what a user would see. When it needs a setup or an action the kit lacks, add a trait or verb to the kit instead of building it in the spec.
|
|
470
491
|
|
|
@@ -496,20 +517,32 @@ accounts.it("removing Bob ends his session", [bobIsSignedIn()], function* ({ rem
|
|
|
496
517
|
|
|
497
518
|
### Pinning time
|
|
498
519
|
|
|
499
|
-
Pass a UTC `DateTime` as the story's `clock` option to pin time before its wrapper, creation, traits and hooks run. Code that uses `Clock` or `DateTime.now` reads that instant. Advance it
|
|
520
|
+
Pass a UTC `DateTime` as the story's `clock` option to pin time before its wrapper, creation, traits and hooks run. Code that uses `Clock` or `DateTime.now` reads that instant. Advance it with native `TestClock.adjust` in a kit verb, so the spec names the time that passes:
|
|
500
521
|
|
|
501
522
|
```ts
|
|
502
|
-
import { DateTime } from "effect";
|
|
503
523
|
import * as TestClock from "effect/testing/TestClock";
|
|
504
524
|
|
|
525
|
+
verbs: (engine, story) => ({
|
|
526
|
+
aDayPasses: () => {
|
|
527
|
+
story.tell("a day passes");
|
|
528
|
+
return TestClock.adjust("1 day");
|
|
529
|
+
},
|
|
530
|
+
}),
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
```ts
|
|
534
|
+
import { DateTime } from "effect";
|
|
535
|
+
|
|
505
536
|
app.it(
|
|
506
|
-
"
|
|
537
|
+
"a day later, the worker shows the next date",
|
|
507
538
|
[],
|
|
508
|
-
function* ({ click, settle, text }) {
|
|
539
|
+
function* ({ aDayPasses, click, settle, text }) {
|
|
509
540
|
yield* click("button");
|
|
510
541
|
yield* settle();
|
|
511
542
|
expect(text("#worker")).toBe("Worker: since Oct 17");
|
|
512
|
-
|
|
543
|
+
|
|
544
|
+
yield* aDayPasses();
|
|
545
|
+
|
|
513
546
|
yield* click("button");
|
|
514
547
|
yield* settle();
|
|
515
548
|
expect(text("#worker")).toBe("Worker: since Oct 18");
|
|
@@ -639,27 +672,48 @@ yield* seedCookies(cookies);
|
|
|
639
672
|
|
|
640
673
|
Happy-dom's detached window records a location change without loading the next document. `domNavigate(url = window.location.href)` from `@shivaedev/test-story/server/domNavigate.ts` performs that load: it follows HTTP redirects through the document transport, keeps cookies for each destination, sets the final location, writes the returned HTML and returns the happy-dom response. Call it after the sign-in client has set the provider location, and before checking the returned page. An unrouted external redirect fails with its hostname.
|
|
641
674
|
|
|
642
|
-
The
|
|
675
|
+
The server package's [social application kit](https://github.com/ShivaeDev/platform/blob/main/packages/server/src/test-support/better-auth/socialApp.ts) runs a fixture Better Auth host on real PostgreSQL with a fake GitHub provider. Its `create` hook acquires the provider and uses scoped `routeOutbound` routing for both `github.com` and `api.github.com`. The fake's authorize endpoint returns the application's callback URL with the received state and a test code. The real callback exchanges that code and fetches the user against the fake, creates the account and session in PostgreSQL, and redirects to the signed-in page.
|
|
643
676
|
|
|
644
|
-
The kit
|
|
677
|
+
The kit creates a Better Auth client whose `customFetchImpl` is `domFetch(baseUrl)`. The story calls `signInWithGitHub`, which sets the provider location, and `followRedirect`, which runs `domNavigate`, then reads the session the document's cookie carries. The provider uses `fakeHttpService`. The authorize, token and user requests at the fake and a later session response provide evidence across the provider and application boundaries. The kit does not copy cookies into request headers.
|
|
645
678
|
|
|
646
679
|
```ts
|
|
647
|
-
socialApp.it(
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
const response = yield* followRedirect();
|
|
654
|
-
expect(response.status).toBe(200);
|
|
655
|
-
expect(heading()).toBe("Signed in as alice@social.test");
|
|
656
|
-
expect(cookie()).not.toContain("session_token");
|
|
657
|
-
expect(yield* session()).toMatchObject({ user: { email: "alice@social.test" } });
|
|
658
|
-
},
|
|
659
|
-
);
|
|
680
|
+
socialApp.it("a social sign-in returns with a cookie session", [], function* ({ signInWithGitHub, followRedirect, session }) {
|
|
681
|
+
yield* signInWithGitHub();
|
|
682
|
+
yield* followRedirect();
|
|
683
|
+
|
|
684
|
+
expect(yield* session()).toMatchObject({ user: { email: "alice@social.test" } });
|
|
685
|
+
});
|
|
660
686
|
```
|
|
661
687
|
|
|
662
|
-
`domFetch`
|
|
688
|
+
`domFetch` defaults to the current window and its cookie jar. The DOM environment keeps one window per test file, and every story starts with no cookies, `localStorage` or `sessionStorage`, so a story never sees the session an earlier story left. The page location and document carry over; run stories using that window serially and let the application's cleanup restore the page location and close its host. Cookies follow hostnames, not listener ports, so a different loopback port alone does not isolate accounts within one story.
|
|
689
|
+
|
|
690
|
+
#### Several members on one host
|
|
691
|
+
|
|
692
|
+
Use `memberScreens` from `@shivaedev/test-story/server/memberScreens.ts` inside a DOM kit's `create` hook. Supply `baseUrl`, `mount(member)` returning an Effect, and `verbs(member, tell)` returning that member's verbs and readouts. Each `MemberScreen` carries its `name`, `fetch`, `registry` and `root`. Mount the application into that root with that registry, and give its auth and HTTP clients the member's fetch. Cookie contexts are independent even when every member uses the same host.
|
|
693
|
+
|
|
694
|
+
A trait calls `yield* members.open("ada", cookies)` with a minted session's cookies. The kit's verbs hook returns `members.verbs(story.tell)`, exposing `as("ada")` to the spec. Member narration includes the name. The calling Scope closes every cookie context, disposes every registry and removes every root. Register renderer unmounting in the mount hook with `Effect.acquireRelease` so it runs before the registry and root are released.
|
|
695
|
+
|
|
696
|
+
```ts
|
|
697
|
+
sharedLists.it("grace sees ada's addition", [signedInMembers("ada", "grace")], function* ({ as }) {
|
|
698
|
+
yield* as("ada").enter("input", "Bread");
|
|
699
|
+
yield* as("ada").submit();
|
|
700
|
+
yield* as("ada").settle();
|
|
701
|
+
yield* as("grace").click({ role: "button", name: "Refresh" });
|
|
702
|
+
yield* as("grace").settle();
|
|
703
|
+
|
|
704
|
+
expect(as("grace").text("output")).toBe("grace's list: ada: Bread");
|
|
705
|
+
});
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
### Rendering React components
|
|
709
|
+
|
|
710
|
+
Use `render`, `eventually`, `captureReactWarnings` and `expectNoReactWarnings` from `@shivaedev/test-story/client/react.ts` in happy-dom tests. Install the optional peers when using this module:
|
|
711
|
+
|
|
712
|
+
```sh
|
|
713
|
+
pnpm add --save-dev react react-dom @effect/atom-react @types/react @types/react-dom happy-dom
|
|
714
|
+
```
|
|
715
|
+
|
|
716
|
+
`render(node, options?)` attaches a React root with its own native atom registry. Its `render(nextNode)` keeps that registry; `unmount()` disposes the root, registry and container. Acquire it with `Effect.acquireRelease` in a story kit so the scope releases it. `captureReactWarnings` acquires a scoped readout of console warnings and caught React errors; `expectNoReactWarnings()` registers a Vitest guard instead. The [React render testing guide](https://github.com/ShivaeDev/platform/tree/main/packages/react#render-tests-in-happy-dom) shows the helpers with a native RPC component and explains the act wait and error declarations.
|
|
663
717
|
|
|
664
718
|
### Driving a screen
|
|
665
719
|
|
|
@@ -680,6 +734,8 @@ verbs: ({ view, requests }, story) =>
|
|
|
680
734
|
|
|
681
735
|
`click(selector)`, `enter(selector, value)` and `submit(selector = "form")` return Effects. Selectors identify exactly one descendant of the root; missing or ambiguous controls fail. Hidden targets and targets inside hidden ancestors refuse actions and readouts. Text entry focuses an input or textarea and dispatches input and change events. Disabled controls refuse clicks and entry, inert ancestors also prevent form submission, and read-only fields refuse entry. Actions do not wait for settlement, so a story can release a held request before calling `settle()`.
|
|
682
736
|
|
|
737
|
+
`within(container)` returns the same driver scoped to that container, including nested `within` calls. Pass a selector, a role/name target or an `HTMLElement`. Selector and role containers must resolve to one rendered descendant and use the usual missing or ambiguous target diagnostics. For example, `within({ role: "region", name: "Billing" }).click({ role: "button", name: "Save" })` can address a Save button when Delivery has an identical button. Settlement keeps the original pending signal and error type.
|
|
738
|
+
|
|
683
739
|
`text(selector?)` concatenates visible HTML text nodes from the selected element or the whole root, without CSS text transforms or layout line breaks. `value(selector)` returns the current input or textarea value. Both narrate what they read through `tell` and leave assertions to the spec. Entry narration omits the supplied value.
|
|
684
740
|
|
|
685
741
|
`click`, `enter`, `submit`, `text` and `value` also accept a `ScreenTarget` object such as `{ role: "button", name: "Save" }` or `{ role: "textbox", name: /email/i }`. The role and computed accessible name must match exactly when strings are used; regular expressions match the name. Like Testing Library's role queries, these targets exclude hidden elements, including `aria-hidden` ancestors. Missing or ambiguous targets fail with the requested role, name and the visible candidates on screen. Narration names the role and name instead of a selector.
|
|
@@ -702,10 +758,11 @@ Import each module with the prefix `@shivaedev/test-story/`; there is no root en
|
|
|
702
758
|
| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
703
759
|
| `server/storyKit.ts` | `storyKit`, `Trait`, `RunUntilOptions`, `Story`, `RunHooks`, `StoryKitDefinition`, `Told`, `StoryBody`, `StoryTest`, `StoryIt`, `StoryKit` |
|
|
704
760
|
| `server/outcomes.ts` | `outcomes(rows)` |
|
|
705
|
-
| `server/domFetch.ts` | `domFetch(baseUrl)`
|
|
706
|
-
| `server/seedCookies.ts` | `seedCookies(cookies)`, `DomCookie`
|
|
761
|
+
| `server/domFetch.ts` | `domFetch(baseUrl, target?)` |
|
|
762
|
+
| `server/seedCookies.ts` | `seedCookies(cookies, target?)`, `DomCookie` |
|
|
707
763
|
| `server/routeOutbound.ts` | `routeOutbound(routes)` |
|
|
708
764
|
| `server/screenDriver.ts` | `screenDriver(options)`, `ScreenDriverOptions`, `ScreenDriver`, `ScreenTarget`, `MissingScreenPending` |
|
|
765
|
+
| `server/memberScreens.ts` | `memberScreens(options)`, `MemberScreen` |
|
|
709
766
|
| `server/domNavigate.ts` | `domNavigate(url?)` |
|
|
710
767
|
| `server/genreTags.ts` | `genreTags(...kitNames)`, `GenreTag` |
|
|
711
768
|
| `server/domEnvironment.config.ts` | Default Vitest environment preserving Node host globals and happy-dom document transport |
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Effect, Scope } from "effect";
|
|
2
|
+
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
3
|
+
import { type ReactNode } from "react";
|
|
4
|
+
import { type RootOptions } from "react-dom/client";
|
|
5
|
+
type CaughtErrorHandler = NonNullable<RootOptions["onCaughtError"]>;
|
|
6
|
+
export interface ReactWarningsReadout {
|
|
7
|
+
readonly caughtErrors: readonly unknown[];
|
|
8
|
+
readonly consoleErrors: readonly (readonly unknown[])[];
|
|
9
|
+
}
|
|
10
|
+
export interface ReactWarnings {
|
|
11
|
+
readonly expectCaughtError: (matches: (error: unknown) => boolean) => CaughtErrorHandler;
|
|
12
|
+
readonly onCaughtError: CaughtErrorHandler;
|
|
13
|
+
readonly read: () => ReactWarningsReadout;
|
|
14
|
+
}
|
|
15
|
+
export declare const captureReactWarnings: Effect.Effect<ReactWarnings, never, Scope.Scope>;
|
|
16
|
+
export declare function expectNoReactWarnings(): {
|
|
17
|
+
expectCaughtError(matches: (error: unknown) => boolean): NonNullable<RootOptions["onCaughtError"]>;
|
|
18
|
+
};
|
|
19
|
+
export declare function eventually(assert: () => void): Effect.Effect<void, Error, never>;
|
|
20
|
+
export interface Rendered {
|
|
21
|
+
readonly container: HTMLDivElement;
|
|
22
|
+
readonly registry: AtomRegistry.AtomRegistry;
|
|
23
|
+
readonly render: (node: ReactNode) => Promise<void>;
|
|
24
|
+
readonly unmount: () => Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
export declare function render(node: ReactNode, options?: RootOptions): Promise<Rendered>;
|
|
27
|
+
export {};
|
|
28
|
+
//# sourceMappingURL=react.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"react.d.ts","sourceRoot":"","sources":["../../src/client/react.ts"],"names":[],"mappings":"AACA,OAAO,EAAS,MAAM,EAAQ,KAAK,EAAE,MAAM,QAAQ,CAAC;AACpD,OAAO,KAAK,YAAY,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAsB,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAC3D,OAAO,EAAc,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAKhE,KAAK,kBAAkB,GAAG,WAAW,CAAC,WAAW,CAAC,eAAe,CAAC,CAAC,CAAC;AAEpE,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,YAAY,EAAE,SAAS,OAAO,EAAE,CAAC;IAC1C,QAAQ,CAAC,aAAa,EAAE,SAAS,CAAC,SAAS,OAAO,EAAE,CAAC,EAAE,CAAC;CACxD;AAED,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,iBAAiB,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,KAAK,kBAAkB,CAAC;IACzF,QAAQ,CAAC,aAAa,EAAE,kBAAkB,CAAC;IAC3C,QAAQ,CAAC,IAAI,EAAE,MAAM,oBAAoB,CAAC;CAC1C;AAqCD,eAAO,MAAM,oBAAoB,kDAA6D,CAAC;AAE/F,wBAAgB,qBAAqB;IAkBnC,iBAAiB,UAAU,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,GAAG,WAAW,CAAC,WAAW,CAAC,eAAe,CAAC,CAAC;EAInG;AACD,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,IAAI,qCAwB5C;AACD,MAAM,WAAW,QAAQ;IACxB,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC;IACnC,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC,YAAY,CAAC;IAC7C,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,SAAS,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpD,QAAQ,CAAC,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AACD,wBAAsB,MAAM,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CA4BtF"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { RegistryContext } from "@effect/atom-react";
|
|
2
|
+
import { Clock, Effect, Exit, Scope } from "effect";
|
|
3
|
+
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
4
|
+
import { act, createElement } from "react";
|
|
5
|
+
import { createRoot } from "react-dom/client";
|
|
6
|
+
import { beforeEach, expect, vi } from "vitest";
|
|
7
|
+
import { eventually as retry } from "@shivaedev/test/eventually.ts";
|
|
8
|
+
import { withLive } from "@shivaedev/test/withLive.ts";
|
|
9
|
+
const acquireReactWarnings = Effect.acquireRelease(Effect.sync(() => {
|
|
10
|
+
const errors = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
|
11
|
+
let consoleErrors;
|
|
12
|
+
const caughtErrors = [];
|
|
13
|
+
const expectations = [];
|
|
14
|
+
const capture = {
|
|
15
|
+
expectCaughtError: (matches) => {
|
|
16
|
+
const expectation = { caught: false };
|
|
17
|
+
expectations.push(expectation);
|
|
18
|
+
return (error) => {
|
|
19
|
+
if (matches(error)) {
|
|
20
|
+
expectation.caught = true;
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
caughtErrors.push(error);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
},
|
|
27
|
+
onCaughtError: (error) => {
|
|
28
|
+
caughtErrors.push(error);
|
|
29
|
+
},
|
|
30
|
+
read: () => ({ caughtErrors: [...caughtErrors], consoleErrors: consoleErrors ?? errors.mock.calls.map((args) => [...args]) }),
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
capture,
|
|
34
|
+
expectations,
|
|
35
|
+
restore: () => {
|
|
36
|
+
consoleErrors = capture.read().consoleErrors;
|
|
37
|
+
errors.mockRestore();
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}), ({ restore }) => Effect.sync(restore));
|
|
41
|
+
export const captureReactWarnings = Effect.map(acquireReactWarnings, ({ capture }) => capture);
|
|
42
|
+
export function expectNoReactWarnings() {
|
|
43
|
+
let current;
|
|
44
|
+
beforeEach(({ onTestFinished }) => {
|
|
45
|
+
const scope = Effect.runSync(Scope.make());
|
|
46
|
+
current = Effect.runSync(Effect.provideService(acquireReactWarnings, Scope.Scope, scope));
|
|
47
|
+
const { capture, expectations } = current;
|
|
48
|
+
onTestFinished(() => {
|
|
49
|
+
Effect.runSync(Scope.close(scope, Exit.void));
|
|
50
|
+
const { consoleErrors, caughtErrors } = capture.read();
|
|
51
|
+
expect(consoleErrors).toEqual([]);
|
|
52
|
+
expect(caughtErrors, "Unexpected caught React errors").toEqual([]);
|
|
53
|
+
expect(expectations.every(({ caught }) => caught), "Expected caught React error did not occur").toBe(true);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
return {
|
|
57
|
+
expectCaughtError(matches) {
|
|
58
|
+
return current.capture.expectCaughtError(matches);
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
export function eventually(assert) {
|
|
63
|
+
return withLive(Effect.gen(function* () {
|
|
64
|
+
const started = yield* Clock.currentTimeMillis;
|
|
65
|
+
return yield* retry(Effect.try({ catch: (error) => error, try: assert }), {
|
|
66
|
+
timeout: "3 seconds",
|
|
67
|
+
// Responses and React updates must settle together inside act.
|
|
68
|
+
wait: Effect.promise(() => act(async () => {
|
|
69
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
70
|
+
})),
|
|
71
|
+
}).pipe(Effect.catch((error) => Effect.gen(function* () {
|
|
72
|
+
const elapsed = (yield* Clock.currentTimeMillis) - started;
|
|
73
|
+
return yield* Effect.fail(new Error(`Assertion did not pass after ${elapsed}ms: ${error instanceof Error ? error.message : String(error)}`, { cause: error }));
|
|
74
|
+
})));
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
export async function render(node, options) {
|
|
78
|
+
const registry = AtomRegistry.make();
|
|
79
|
+
const container = document.createElement("div");
|
|
80
|
+
document.body.append(container);
|
|
81
|
+
const root = createRoot(container, options);
|
|
82
|
+
let mounted = true;
|
|
83
|
+
async function unmount() {
|
|
84
|
+
if (!mounted) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
mounted = false;
|
|
88
|
+
try {
|
|
89
|
+
await act(async () => root.unmount());
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
registry.dispose();
|
|
93
|
+
container.remove();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async function update(next) {
|
|
97
|
+
await act(async () => root.render(createElement(RegistryContext.Provider, { value: registry }, next)));
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
await update(node);
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
await unmount();
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
return { container, registry, render: update, unmount };
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=react.js.map
|