@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
|
@@ -0,0 +1,142 @@
|
|
|
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, type ReactNode } from "react";
|
|
5
|
+
import { createRoot, type RootOptions } 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
|
+
|
|
10
|
+
type CaughtErrorHandler = NonNullable<RootOptions["onCaughtError"]>;
|
|
11
|
+
|
|
12
|
+
export interface ReactWarningsReadout {
|
|
13
|
+
readonly caughtErrors: readonly unknown[];
|
|
14
|
+
readonly consoleErrors: readonly (readonly unknown[])[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ReactWarnings {
|
|
18
|
+
readonly expectCaughtError: (matches: (error: unknown) => boolean) => CaughtErrorHandler;
|
|
19
|
+
readonly onCaughtError: CaughtErrorHandler;
|
|
20
|
+
readonly read: () => ReactWarningsReadout;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const acquireReactWarnings = Effect.acquireRelease(
|
|
24
|
+
Effect.sync(() => {
|
|
25
|
+
const errors = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
|
26
|
+
let consoleErrors: readonly (readonly unknown[])[] | undefined;
|
|
27
|
+
const caughtErrors: unknown[] = [];
|
|
28
|
+
const expectations: { caught: boolean }[] = [];
|
|
29
|
+
const capture: ReactWarnings = {
|
|
30
|
+
expectCaughtError: (matches) => {
|
|
31
|
+
const expectation = { caught: false };
|
|
32
|
+
expectations.push(expectation);
|
|
33
|
+
return (error) => {
|
|
34
|
+
if (matches(error)) {
|
|
35
|
+
expectation.caught = true;
|
|
36
|
+
} else {
|
|
37
|
+
caughtErrors.push(error);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
onCaughtError: (error) => {
|
|
42
|
+
caughtErrors.push(error);
|
|
43
|
+
},
|
|
44
|
+
read: () => ({ caughtErrors: [...caughtErrors], consoleErrors: consoleErrors ?? errors.mock.calls.map((args) => [...args]) }),
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
capture,
|
|
48
|
+
expectations,
|
|
49
|
+
restore: () => {
|
|
50
|
+
consoleErrors = capture.read().consoleErrors;
|
|
51
|
+
errors.mockRestore();
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}),
|
|
55
|
+
({ restore }) => Effect.sync(restore),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
export const captureReactWarnings = Effect.map(acquireReactWarnings, ({ capture }) => capture);
|
|
59
|
+
|
|
60
|
+
export function expectNoReactWarnings() {
|
|
61
|
+
let current: Effect.Success<typeof acquireReactWarnings>;
|
|
62
|
+
beforeEach(({ onTestFinished }) => {
|
|
63
|
+
const scope = Effect.runSync(Scope.make());
|
|
64
|
+
current = Effect.runSync(Effect.provideService(acquireReactWarnings, Scope.Scope, scope));
|
|
65
|
+
const { capture, expectations } = current;
|
|
66
|
+
onTestFinished(() => {
|
|
67
|
+
Effect.runSync(Scope.close(scope, Exit.void));
|
|
68
|
+
const { consoleErrors, caughtErrors } = capture.read();
|
|
69
|
+
expect(consoleErrors).toEqual([]);
|
|
70
|
+
expect(caughtErrors, "Unexpected caught React errors").toEqual([]);
|
|
71
|
+
expect(
|
|
72
|
+
expectations.every(({ caught }) => caught),
|
|
73
|
+
"Expected caught React error did not occur",
|
|
74
|
+
).toBe(true);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
return {
|
|
78
|
+
expectCaughtError(matches: (error: unknown) => boolean): NonNullable<RootOptions["onCaughtError"]> {
|
|
79
|
+
return current.capture.expectCaughtError(matches);
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
export function eventually(assert: () => void) {
|
|
84
|
+
return withLive(
|
|
85
|
+
Effect.gen(function* () {
|
|
86
|
+
const started = yield* Clock.currentTimeMillis;
|
|
87
|
+
return yield* retry(Effect.try({ catch: (error) => error, try: assert }), {
|
|
88
|
+
timeout: "3 seconds",
|
|
89
|
+
// Responses and React updates must settle together inside act.
|
|
90
|
+
wait: Effect.promise(() =>
|
|
91
|
+
act(async () => {
|
|
92
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 10));
|
|
93
|
+
}),
|
|
94
|
+
),
|
|
95
|
+
}).pipe(
|
|
96
|
+
Effect.catch((error) =>
|
|
97
|
+
Effect.gen(function* () {
|
|
98
|
+
const elapsed = (yield* Clock.currentTimeMillis) - started;
|
|
99
|
+
return yield* Effect.fail(
|
|
100
|
+
new Error(`Assertion did not pass after ${elapsed}ms: ${error instanceof Error ? error.message : String(error)}`, { cause: error }),
|
|
101
|
+
);
|
|
102
|
+
}),
|
|
103
|
+
),
|
|
104
|
+
);
|
|
105
|
+
}),
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
export interface Rendered {
|
|
109
|
+
readonly container: HTMLDivElement;
|
|
110
|
+
readonly registry: AtomRegistry.AtomRegistry;
|
|
111
|
+
readonly render: (node: ReactNode) => Promise<void>;
|
|
112
|
+
readonly unmount: () => Promise<void>;
|
|
113
|
+
}
|
|
114
|
+
export async function render(node: ReactNode, options?: RootOptions): Promise<Rendered> {
|
|
115
|
+
const registry = AtomRegistry.make();
|
|
116
|
+
const container = document.createElement("div");
|
|
117
|
+
document.body.append(container);
|
|
118
|
+
const root = createRoot(container, options);
|
|
119
|
+
let mounted = true;
|
|
120
|
+
async function unmount() {
|
|
121
|
+
if (!mounted) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
mounted = false;
|
|
125
|
+
try {
|
|
126
|
+
await act(async () => root.unmount());
|
|
127
|
+
} finally {
|
|
128
|
+
registry.dispose();
|
|
129
|
+
container.remove();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async function update(next: ReactNode) {
|
|
133
|
+
await act(async () => root.render(createElement(RegistryContext.Provider, { value: registry }, next)));
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
await update(node);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
await unmount();
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
return { container, registry, render: update, unmount };
|
|
142
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
import { GlobalWindow } from "happy-dom";
|
|
3
|
+
import WindowBrowserContext from "happy-dom/lib/window/WindowBrowserContext.js";
|
|
3
4
|
import { type Environment, populateGlobal } from "vitest/runtime";
|
|
4
5
|
|
|
5
6
|
const domEnvironment: Environment = {
|
|
@@ -28,7 +29,12 @@ const domEnvironment: Environment = {
|
|
|
28
29
|
}
|
|
29
30
|
Object.defineProperty(global, "window", { configurable: true, value: win, writable: true });
|
|
30
31
|
Object.defineProperty(win.document, "defaultView", { configurable: true, get: () => win });
|
|
31
|
-
|
|
32
|
+
function freshDocument() {
|
|
33
|
+
new WindowBrowserContext(win).getBrowserContext()?.cookieContainer.clearCookies();
|
|
34
|
+
win.localStorage.clear();
|
|
35
|
+
win.sessionStorage.clear();
|
|
36
|
+
}
|
|
37
|
+
Object.defineProperty(global, Symbol.for("test-story.dom"), { configurable: true, value: freshDocument });
|
|
32
38
|
return {
|
|
33
39
|
async teardown(target) {
|
|
34
40
|
try {
|
package/src/server/domFetch.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
export function domFetch(
|
|
1
|
+
export function domFetch(
|
|
2
|
+
baseUrl: string,
|
|
3
|
+
target: { readonly fetch: typeof globalThis.fetch; readonly location: { href: string } } = window,
|
|
4
|
+
): typeof globalThis.fetch {
|
|
2
5
|
const base = new URL(baseUrl);
|
|
3
|
-
|
|
4
|
-
const transport =
|
|
6
|
+
target.location.href = base.href;
|
|
7
|
+
const transport = target.fetch.bind(target);
|
|
5
8
|
return (input, init) => {
|
|
6
9
|
if (input instanceof Request) {
|
|
7
10
|
const request = new Request(input, init);
|
|
@@ -75,15 +75,13 @@ export const fakeHttpService = Effect.fnUntraced(function* (options: FakeHttpSer
|
|
|
75
75
|
const controls = fakeHttpControls(tell, () => clock.currentTimeMillisUnsafe());
|
|
76
76
|
const server = createServer((request, response) => fakeHttpReceive(request, response, options, requests, controls, tell));
|
|
77
77
|
const url = yield* loopbackServer(server);
|
|
78
|
-
yield* Effect.addFinalizer(
|
|
78
|
+
yield* Effect.addFinalizer(controls.close);
|
|
79
79
|
function checkRoute(route: string) {
|
|
80
80
|
if (!Object.hasOwn(options.routes, route)) {
|
|
81
81
|
throw new Error(`Unknown fake HTTP route "${route}".\nhelp: Use a name from fakeHttpService's routes when scripting a reply or hold.`);
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
return {
|
|
85
|
-
failOnce: (route: string, reply: FakeHttpReplySource, scope?: FakeHttpScope) =>
|
|
86
|
-
Effect.sync(() => checkRoute(route)).pipe(Effect.andThen(controls.queue(route, reply, scope))),
|
|
87
85
|
fault: (route: string, fault: FakeHttpFault, scope?: FakeHttpScope) =>
|
|
88
86
|
Effect.sync(() => checkRoute(route)).pipe(Effect.andThen(controls.fault(route, fault, scope))),
|
|
89
87
|
hold: (route: string, holdOptions?: FakeHttpHoldOptions) =>
|
|
@@ -96,8 +94,6 @@ export const fakeHttpService = Effect.fnUntraced(function* (options: FakeHttpSer
|
|
|
96
94
|
checkRoute(route);
|
|
97
95
|
checkRoute(arrival);
|
|
98
96
|
}).pipe(Effect.andThen(controls.releaseOnArrival(route, arrival, scope))),
|
|
99
|
-
replyOnce: (route: string, reply: FakeHttpReplySource, scope?: FakeHttpScope) =>
|
|
100
|
-
Effect.sync(() => checkRoute(route)).pipe(Effect.andThen(controls.queue(route, reply, scope))),
|
|
101
97
|
get requests(): readonly FakeHttpRequestRecord[] {
|
|
102
98
|
return requests.slice();
|
|
103
99
|
},
|
|
@@ -31,7 +31,12 @@ export const forwardingProxy = Effect.fnUntraced(function* (upstream: string, op
|
|
|
31
31
|
method: incoming.method,
|
|
32
32
|
};
|
|
33
33
|
}
|
|
34
|
+
let offline = false;
|
|
34
35
|
const forward: RequestListener = (incoming, response) => {
|
|
36
|
+
if (offline) {
|
|
37
|
+
incoming.destroy();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
35
40
|
const outgoing = request(`${upstream}${incoming.url}`, requestOptions(incoming), (result) => {
|
|
36
41
|
response.writeHead(result.statusCode ?? HttpStatus.fromLiteral("BadGateway"), result.headers);
|
|
37
42
|
result.pipe(response);
|
|
@@ -48,31 +53,38 @@ export const forwardingProxy = Effect.fnUntraced(function* (upstream: string, op
|
|
|
48
53
|
};
|
|
49
54
|
const sockets = new Set<Duplex>();
|
|
50
55
|
function server() {
|
|
51
|
-
return createServer(forward)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
downstream.
|
|
56
|
+
return createServer(forward)
|
|
57
|
+
.on("connection", (socket) => {
|
|
58
|
+
sockets.add(socket);
|
|
59
|
+
socket.on("close", () => sockets.delete(socket));
|
|
60
|
+
})
|
|
61
|
+
.on("upgrade", (incoming, downstream, head) => {
|
|
62
|
+
if (offline) {
|
|
63
|
+
downstream.destroy();
|
|
64
|
+
return;
|
|
59
65
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
+
const outgoing = request(`${upstream}${incoming.url}`, requestOptions(incoming));
|
|
67
|
+
outgoing.on("upgrade", (result, upstreamSocket, upstreamHead) => {
|
|
68
|
+
downstream.write(`HTTP/1.1 ${result.statusCode} ${result.statusMessage}\r\n`);
|
|
69
|
+
for (let index = 0; index < result.rawHeaders.length; index += 2) {
|
|
70
|
+
downstream.write(`${result.rawHeaders[index]}: ${result.rawHeaders[index + 1]}\r\n`);
|
|
71
|
+
}
|
|
72
|
+
downstream.write("\r\n");
|
|
73
|
+
downstream.write(upstreamHead);
|
|
74
|
+
upstreamSocket.write(head);
|
|
75
|
+
downstream.pipe(upstreamSocket).pipe(downstream);
|
|
76
|
+
downstream.on("close", () => upstreamSocket.destroy());
|
|
77
|
+
upstreamSocket.on("error", () => downstream.destroy());
|
|
78
|
+
});
|
|
79
|
+
outgoing.on("response", (result) => {
|
|
80
|
+
downstream.end(`HTTP/1.1 ${result.statusCode} ${result.statusMessage}\r\nConnection: close\r\n\r\n`);
|
|
81
|
+
result.resume();
|
|
82
|
+
});
|
|
83
|
+
outgoing.on("error", () => downstream.destroy());
|
|
84
|
+
downstream.on("error", () => outgoing.destroy());
|
|
85
|
+
downstream.on("close", () => outgoing.destroy());
|
|
86
|
+
outgoing.end();
|
|
66
87
|
});
|
|
67
|
-
outgoing.on("response", (result) => {
|
|
68
|
-
downstream.end(`HTTP/1.1 ${result.statusCode} ${result.statusMessage}\r\nConnection: close\r\n\r\n`);
|
|
69
|
-
result.resume();
|
|
70
|
-
});
|
|
71
|
-
outgoing.on("error", () => downstream.destroy());
|
|
72
|
-
downstream.on("error", () => outgoing.destroy());
|
|
73
|
-
downstream.on("close", () => outgoing.destroy());
|
|
74
|
-
outgoing.end();
|
|
75
|
-
});
|
|
76
88
|
}
|
|
77
89
|
const url = yield* loopbackServer(server());
|
|
78
90
|
yield* loopbackServer(server(), { host: "::1", port: Number(new URL(url).port) });
|
|
@@ -83,5 +95,16 @@ export const forwardingProxy = Effect.fnUntraced(function* (upstream: string, op
|
|
|
83
95
|
}
|
|
84
96
|
}),
|
|
85
97
|
);
|
|
86
|
-
return {
|
|
98
|
+
return {
|
|
99
|
+
disconnect: () => {
|
|
100
|
+
offline = true;
|
|
101
|
+
for (const socket of sockets) {
|
|
102
|
+
socket.destroy();
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
resume: () => {
|
|
106
|
+
offline = false;
|
|
107
|
+
},
|
|
108
|
+
url,
|
|
109
|
+
};
|
|
87
110
|
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Response as BrowserResponse, BrowserWindow } from "happy-dom";
|
|
2
|
+
|
|
3
|
+
function responseBody(response: BrowserResponse, release: () => void) {
|
|
4
|
+
if (response.body === null) {
|
|
5
|
+
release();
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
const reader = response.body.getReader();
|
|
9
|
+
return new ReadableStream<Uint8Array>({
|
|
10
|
+
async cancel(reason) {
|
|
11
|
+
release();
|
|
12
|
+
await reader.cancel(reason);
|
|
13
|
+
},
|
|
14
|
+
async pull(controller) {
|
|
15
|
+
try {
|
|
16
|
+
const next = await reader.read();
|
|
17
|
+
if (next.done) {
|
|
18
|
+
release();
|
|
19
|
+
controller.close();
|
|
20
|
+
} else {
|
|
21
|
+
controller.enqueue(next.value);
|
|
22
|
+
}
|
|
23
|
+
} catch (error) {
|
|
24
|
+
release();
|
|
25
|
+
controller.error(error);
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function memberFetch(browser: BrowserWindow): typeof globalThis.fetch {
|
|
32
|
+
return async (input, init) => {
|
|
33
|
+
const request = new Request(input, init);
|
|
34
|
+
const controller = new browser.AbortController();
|
|
35
|
+
function abort() {
|
|
36
|
+
controller.abort(request.signal.reason);
|
|
37
|
+
}
|
|
38
|
+
function release() {
|
|
39
|
+
request.signal.removeEventListener("abort", abort);
|
|
40
|
+
}
|
|
41
|
+
request.signal.addEventListener("abort", abort, { once: true });
|
|
42
|
+
if (request.signal.aborted) {
|
|
43
|
+
abort();
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
const response = await browser.fetch(request.url, {
|
|
47
|
+
body: request.body === null ? null : await request.arrayBuffer(),
|
|
48
|
+
credentials: request.credentials,
|
|
49
|
+
headers: [...request.headers],
|
|
50
|
+
method: request.method,
|
|
51
|
+
redirect: request.redirect,
|
|
52
|
+
signal: controller.signal,
|
|
53
|
+
});
|
|
54
|
+
const result = new Response(responseBody(response, release), {
|
|
55
|
+
headers: [...response.headers],
|
|
56
|
+
status: response.status,
|
|
57
|
+
statusText: response.statusText,
|
|
58
|
+
});
|
|
59
|
+
Object.defineProperty(result, "url", { value: response.url });
|
|
60
|
+
Object.defineProperty(result, "redirected", { value: response.redirected });
|
|
61
|
+
return result;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
release();
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -27,6 +27,7 @@ export function compose(name: string, kits: KitList): LooseDefinition {
|
|
|
27
27
|
layer: definitions.reduce<AnyTestLayer>((layer, definition) => Layer.merge(layer, definition.layer ?? Layer.empty), Layer.empty),
|
|
28
28
|
name,
|
|
29
29
|
outbound: Object.assign({}, ...definitions.map((definition) => definition.outbound)),
|
|
30
|
+
outboundPassthrough: definitions.some((definition) => definition.outboundPassthrough === true),
|
|
30
31
|
runIf: definitions.every((definition) => definition.runIf !== false),
|
|
31
32
|
stages: definitions.flatMap((definition) => definition.stages),
|
|
32
33
|
verbs: (engine, story) => {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
|
|
3
|
+
const DOM = Symbol.for("test-story.dom");
|
|
4
|
+
|
|
5
|
+
export function inDom() {
|
|
6
|
+
return typeof Reflect.get(globalThis, DOM) === "function";
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// The DOM environment keeps one window per file, so each story clears what an earlier story stored in it.
|
|
10
|
+
export const freshDocument = Effect.sync(() => {
|
|
11
|
+
const clear: unknown = Reflect.get(globalThis, DOM);
|
|
12
|
+
if (typeof clear === "function") {
|
|
13
|
+
clear();
|
|
14
|
+
}
|
|
15
|
+
});
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { ServerResponse } from "node:http";
|
|
2
2
|
import { Effect } from "effect";
|
|
3
|
-
import * as HttpStatus from "effect/http/HttpStatus";
|
|
4
3
|
import type {
|
|
5
4
|
FakeHttpFault,
|
|
6
5
|
FakeHttpHoldOptions,
|
|
@@ -13,8 +12,11 @@ import { fakeHttpGates } from "#internal/fakeHttpGates.ts";
|
|
|
13
12
|
import { fakeHttpScripts } from "#internal/fakeHttpScripts.ts";
|
|
14
13
|
import { fakeHttpSelection } from "#internal/fakeHttpSelection.ts";
|
|
15
14
|
import { fakeHttpConnection, fakeHttpSend } from "#internal/fakeHttpSend.ts";
|
|
15
|
+
import { describeValue } from "#internal/render.ts";
|
|
16
|
+
import { explained } from "#internal/wrap.ts";
|
|
16
17
|
|
|
17
18
|
export function fakeHttpControls(tell: (line: string) => void, now: () => number) {
|
|
19
|
+
let failure: Error | undefined;
|
|
18
20
|
const scripts = fakeHttpScripts(tell);
|
|
19
21
|
const holds = fakeHttpGates(tell, "hold");
|
|
20
22
|
const stalls = fakeHttpGates(tell, "stall");
|
|
@@ -29,7 +31,7 @@ export function fakeHttpControls(tell: (line: string) => void, now: () => number
|
|
|
29
31
|
}
|
|
30
32
|
arrivals.delete(route);
|
|
31
33
|
},
|
|
32
|
-
close: ()
|
|
34
|
+
close: Effect.fnUntraced(function* () {
|
|
33
35
|
for (const response of active.keys()) {
|
|
34
36
|
response.destroy();
|
|
35
37
|
}
|
|
@@ -37,6 +39,16 @@ export function fakeHttpControls(tell: (line: string) => void, now: () => number
|
|
|
37
39
|
stalls.close();
|
|
38
40
|
arrivals.clear();
|
|
39
41
|
scripts.clear();
|
|
42
|
+
if (failure !== undefined) {
|
|
43
|
+
yield* Effect.die(failure);
|
|
44
|
+
}
|
|
45
|
+
}),
|
|
46
|
+
failed: (method: string, path: string, cause: unknown) => {
|
|
47
|
+
const message = `fake HTTP could not answer ${method} ${path}: ${describeValue(cause)}`;
|
|
48
|
+
tell(message);
|
|
49
|
+
failure ??= new Error(explained(message, "Fix the fake's handler. To simulate an HTTP failure, return a reply with an error status."), {
|
|
50
|
+
cause,
|
|
51
|
+
});
|
|
40
52
|
},
|
|
41
53
|
fault: (route: string, fault: FakeHttpFault, scope?: FakeHttpScope) =>
|
|
42
54
|
Effect.promise(async () => {
|
|
@@ -65,13 +77,6 @@ export function fakeHttpControls(tell: (line: string) => void, now: () => number
|
|
|
65
77
|
await fakeHttpConnection(response).pause(holds.get(route, request)?.enter());
|
|
66
78
|
return !(response.destroyed || response.writableEnded || response.headersSent);
|
|
67
79
|
},
|
|
68
|
-
queue: (route: string, reply: FakeHttpReplySource, scope?: FakeHttpScope) =>
|
|
69
|
-
Effect.sync(() => {
|
|
70
|
-
scripts.make(route, { kind: "status", reply }, scope, false);
|
|
71
|
-
tell(
|
|
72
|
-
`fake HTTP ${fakeHttpSelection(route, scope).label} will answer once with ${typeof reply === "function" ? "a request-time reply" : (reply.status ?? HttpStatus.fromLiteral("OK"))}`,
|
|
73
|
-
);
|
|
74
|
-
}),
|
|
75
80
|
releaseOnArrival: (route: string, arrival: string, scope?: FakeHttpScope) =>
|
|
76
81
|
Effect.sync(() => {
|
|
77
82
|
const hold = holds.at(route, scope);
|
|
@@ -107,11 +107,7 @@ export async function fakeHttpReceive(
|
|
|
107
107
|
}
|
|
108
108
|
await fakeHttpAnswer(found.name, found.route, request, response, controls, tell);
|
|
109
109
|
} catch (error) {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
response.destroy();
|
|
113
|
-
} else {
|
|
114
|
-
await fakeHttpSend(response, { status: HttpStatus.fromLiteral("InternalServerError") });
|
|
115
|
-
}
|
|
110
|
+
controls.failed(incoming.method ?? "GET", incoming.url ?? "/", error);
|
|
111
|
+
response.destroy();
|
|
116
112
|
}
|
|
117
113
|
}
|
|
@@ -10,13 +10,11 @@ export function fakeHttpScripts(tell: (line: string) => void) {
|
|
|
10
10
|
}>();
|
|
11
11
|
return {
|
|
12
12
|
clear: () => scripts.clear(),
|
|
13
|
-
make: (route: string, fault: FakeHttpFault, options: FakeHttpScriptOptions = {}
|
|
13
|
+
make: (route: string, fault: FakeHttpFault, options: FakeHttpScriptOptions = {}): FakeHttpScript => {
|
|
14
14
|
const selection = fakeHttpSelection(route, options);
|
|
15
15
|
const script = { fault, options, selection };
|
|
16
16
|
scripts.add(script);
|
|
17
|
-
|
|
18
|
-
tell(`fake HTTP ${selection.label} will fault ${fault.kind} ${options.phase ?? "before"} reply ${options.repeat ? "until lifted" : "once"}`);
|
|
19
|
-
}
|
|
17
|
+
tell(`fake HTTP ${selection.label} will fault ${fault.kind} ${options.phase ?? "before"} reply ${options.repeat ? "until lifted" : "once"}`);
|
|
20
18
|
return {
|
|
21
19
|
lift: Effect.sync(() => {
|
|
22
20
|
if (scripts.delete(script)) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Crypto, Effect, Layer, Scope } from "effect";
|
|
2
|
-
import type { AnyEffect,
|
|
2
|
+
import type { AnyEffect, HookEffects, HookValue, ServicesOf } from "#internal/hooked.ts";
|
|
3
3
|
import type { StoryKitDefinition } from "#storyKit.ts";
|
|
4
4
|
|
|
5
5
|
export type AfterResults<TStage extends string> = {
|
|
@@ -26,21 +26,3 @@ export type InferredDefinition<
|
|
|
26
26
|
readonly create: TCreate;
|
|
27
27
|
readonly after?: { readonly [TKey in keyof TAfter]: (engine: HookValue<ReturnType<TCreate>>) => TAfter[TKey] };
|
|
28
28
|
} & LayerFor<HookEffects<ReturnType<TCreate> | TAfter[keyof TAfter]> | TStep | TFailed | TDiagnose, TProvided>;
|
|
29
|
-
|
|
30
|
-
// A synchronous after hook has no effect to infer, so TypeScript leaves it at the AnyEffect constraint.
|
|
31
|
-
type AfterEffects<TAfter> = { readonly [TKey in keyof TAfter]-?: AnyEffect extends TAfter[TKey] ? never : TAfter[TKey] }[keyof TAfter];
|
|
32
|
-
|
|
33
|
-
export type LegacyDefinition<
|
|
34
|
-
TEngine,
|
|
35
|
-
TStage extends string,
|
|
36
|
-
TVerbs,
|
|
37
|
-
TProvided,
|
|
38
|
-
TCreate extends AnyEffect,
|
|
39
|
-
TAfter extends { readonly [TKey in TStage]?: AnyEffect },
|
|
40
|
-
TStep extends AnyEffect,
|
|
41
|
-
TFailed extends AnyEffect,
|
|
42
|
-
TDiagnose extends AnyEffect,
|
|
43
|
-
> = Omit<StoryKitDefinition<TEngine, TStage, TVerbs, TProvided, TCreate, TAfter, TStep, TFailed, TDiagnose>, "create" | "after"> & {
|
|
44
|
-
readonly create: Hook<[], TCreate, TEngine> & (TEngine extends AnyEffect ? never : unknown);
|
|
45
|
-
readonly after?: { readonly [TKey in keyof TAfter]: Hook<[engine: TEngine], TAfter[TKey] & AnyEffect, void> };
|
|
46
|
-
} & LayerFor<TCreate | AfterEffects<TAfter> | TStep | TFailed | TDiagnose, TProvided>;
|
|
@@ -13,7 +13,7 @@ function isDispatcher(value: unknown): value is Dispatcher {
|
|
|
13
13
|
return typeof value === "object" && value !== null && "dispatch" in value && typeof value.dispatch === "function";
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
export async function installOutbound(routes: Readonly<Record<string, string>>, strict =
|
|
16
|
+
export async function installOutbound(routes: Readonly<Record<string, string>>, strict = true) {
|
|
17
17
|
const origins = new Map(Object.entries(routes).map(([hostname, target]) => [hostname, new URL(target).origin]));
|
|
18
18
|
let refused: Error | undefined;
|
|
19
19
|
// A data URL initializes Node's bundled Undici without sending an HTTP request.
|
|
@@ -26,6 +26,7 @@ export interface LooseDefinition {
|
|
|
26
26
|
readonly layer?: AnyTestLayer;
|
|
27
27
|
readonly name: string;
|
|
28
28
|
readonly outbound?: Readonly<Record<string, string>>;
|
|
29
|
+
readonly outboundPassthrough?: boolean;
|
|
29
30
|
readonly run?: LooseRunHooks<unknown>;
|
|
30
31
|
readonly runIf?: boolean;
|
|
31
32
|
readonly stages: readonly string[];
|
|
@@ -4,6 +4,7 @@ import { Effect, Layer } from "effect";
|
|
|
4
4
|
import * as TestCrypto from "effect/testing/TestCrypto";
|
|
5
5
|
import { makeEffectIt } from "@shivaedev/test/makeEffectIt.ts";
|
|
6
6
|
import type { EffectTest, EffectTestOptions } from "@shivaedev/test/types.ts";
|
|
7
|
+
import { freshDocument, inDom } from "#internal/domDocument.ts";
|
|
7
8
|
import { type Genre, genreOf } from "#internal/genre.ts";
|
|
8
9
|
import { type AnyEffect, hooked } from "#internal/hooked.ts";
|
|
9
10
|
import type { LooseDefinition, LooseTrait } from "#internal/seed.ts";
|
|
@@ -54,12 +55,13 @@ function declaring(definition: LooseDefinition, genre: Genre, declare: EffectTes
|
|
|
54
55
|
|
|
55
56
|
export function storyIt(definition: LooseDefinition): LooseIt {
|
|
56
57
|
const genre = genreOf(definition.name);
|
|
57
|
-
const outbound = definition.outbound ?? (
|
|
58
|
+
const outbound = definition.outbound ?? (inDom() ? {} : undefined);
|
|
58
59
|
const { effectApp } = makeEffectIt({
|
|
59
60
|
around: (effect) =>
|
|
60
61
|
Effect.gen(function* () {
|
|
62
|
+
yield* freshDocument;
|
|
61
63
|
if (outbound !== undefined) {
|
|
62
|
-
yield* routeOutbound(outbound);
|
|
64
|
+
yield* routeOutbound(outbound, { passthrough: definition.outboundPassthrough === true });
|
|
63
65
|
}
|
|
64
66
|
return yield* definition.around?.(effect) ?? effect;
|
|
65
67
|
}).pipe(Effect.provide(TestCrypto.layer(0).pipe(Layer.provide(NodeCrypto.layer)))),
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Effect, Option, type Scope } from "effect";
|
|
2
|
+
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
3
|
+
import { GlobalWindow } from "happy-dom";
|
|
4
|
+
import { domFetch } from "#domFetch.ts";
|
|
5
|
+
import { memberFetch } from "#internal/adapters/memberFetch.ts";
|
|
6
|
+
import { documentTransport } from "#internal/documentTransport.ts";
|
|
7
|
+
import { type DomCookie, seedCookies } from "#seedCookies.ts";
|
|
8
|
+
|
|
9
|
+
export interface MemberScreen {
|
|
10
|
+
readonly fetch: typeof globalThis.fetch;
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly registry: AtomRegistry.AtomRegistry;
|
|
13
|
+
readonly root: HTMLDivElement;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function memberScreens<E, R, TVerbs>(options: {
|
|
17
|
+
readonly baseUrl: string;
|
|
18
|
+
readonly mount: (member: MemberScreen) => Effect.Effect<void, E, R | Scope.Scope>;
|
|
19
|
+
readonly verbs: (member: MemberScreen, tell: (line: string) => void) => TVerbs;
|
|
20
|
+
}) {
|
|
21
|
+
const members = new Map<string, MemberScreen>();
|
|
22
|
+
return {
|
|
23
|
+
open: Effect.fnUntraced(function* (name: string, cookies: readonly DomCookie[]) {
|
|
24
|
+
const browser = yield* Effect.acquireRelease(
|
|
25
|
+
Effect.sync(() => new GlobalWindow({ url: options.baseUrl })),
|
|
26
|
+
(target) => Effect.promise(() => target.happyDOM.abort()).pipe(Effect.andThen(Effect.sync(() => target.close()))),
|
|
27
|
+
);
|
|
28
|
+
browser.happyDOM.settings.fetch.interceptor = documentTransport(globalThis.fetch);
|
|
29
|
+
yield* seedCookies(cookies, browser);
|
|
30
|
+
const member = yield* Effect.acquireRelease(
|
|
31
|
+
Effect.sync(() => {
|
|
32
|
+
const root = document.createElement("div");
|
|
33
|
+
document.body.append(root);
|
|
34
|
+
return {
|
|
35
|
+
fetch: domFetch(options.baseUrl, { fetch: memberFetch(browser), location: browser.location }),
|
|
36
|
+
name,
|
|
37
|
+
registry: AtomRegistry.make(),
|
|
38
|
+
root,
|
|
39
|
+
};
|
|
40
|
+
}),
|
|
41
|
+
({ registry, root }) =>
|
|
42
|
+
Effect.sync(() => {
|
|
43
|
+
members.delete(name);
|
|
44
|
+
registry.dispose();
|
|
45
|
+
root.remove();
|
|
46
|
+
}),
|
|
47
|
+
);
|
|
48
|
+
yield* options.mount(member);
|
|
49
|
+
members.set(name, member);
|
|
50
|
+
}),
|
|
51
|
+
verbs: (tell: (line: string) => void) => ({
|
|
52
|
+
as: (name: string) => {
|
|
53
|
+
const member = Option.getOrThrowWith(
|
|
54
|
+
Option.fromUndefinedOr(members.get(name)),
|
|
55
|
+
() => new Error(`No screen is open for ${JSON.stringify(name)}.\nhelp: Open this member in a story trait before using as(name).`),
|
|
56
|
+
);
|
|
57
|
+
return options.verbs(member, (line) => tell(`${name}: ${line}`));
|
|
58
|
+
},
|
|
59
|
+
}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
+
import { inDom } from "#internal/domDocument.ts";
|
|
2
3
|
import { installOutbound } from "#internal/installOutbound.ts";
|
|
3
4
|
|
|
4
|
-
export function routeOutbound(routes: Readonly<Record<string, string
|
|
5
|
+
export function routeOutbound(routes: Readonly<Record<string, string>>, options: { readonly passthrough?: boolean } = {}) {
|
|
5
6
|
return Effect.acquireRelease(
|
|
6
|
-
Effect.promise(() => installOutbound(routes,
|
|
7
|
+
Effect.promise(() => installOutbound(routes, !options.passthrough || inDom())),
|
|
7
8
|
(restore) => Effect.sync(restore),
|
|
8
9
|
).pipe(Effect.asVoid);
|
|
9
10
|
}
|
|
@@ -18,17 +18,30 @@ export class MissingScreenPending extends Data.TaggedError("MissingScreenPending
|
|
|
18
18
|
"Cannot settle the screen without the pending option.\nhelp: Supply pending: () => boolean that reads the application's pending work and stays true until its resulting screen work is ready to render.";
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
export type ScreenDriver<E = never> = Omit<ReturnType<typeof
|
|
21
|
+
export type ScreenDriver<E = never> = Omit<ReturnType<typeof makeScreenActions>, "settle"> & {
|
|
22
22
|
settle: (options?: { readonly timeoutMs?: number }) => Effect.Effect<void, E>;
|
|
23
|
+
within: (container: ScreenTarget | HTMLElement) => ScreenDriver<E>;
|
|
23
24
|
};
|
|
24
25
|
|
|
25
26
|
export function screenDriver(options: ScreenDriverOptions & { readonly pending: () => boolean }): ScreenDriver;
|
|
26
27
|
export function screenDriver(options: ScreenDriverOptions): ScreenDriver<MissingScreenPending>;
|
|
27
|
-
export function screenDriver(options: ScreenDriverOptions) {
|
|
28
|
-
|
|
28
|
+
export function screenDriver(options: ScreenDriverOptions): ScreenDriver<MissingScreenPending> {
|
|
29
|
+
const suppliedRoot = options.root;
|
|
30
|
+
const root = typeof suppliedRoot === "function" ? suppliedRoot : () => suppliedRoot;
|
|
31
|
+
const elements = screenElements(root);
|
|
32
|
+
return {
|
|
33
|
+
...makeScreenActions(options),
|
|
34
|
+
within: (container) => {
|
|
35
|
+
function scopedRoot() {
|
|
36
|
+
return container instanceof HTMLElement ? elements.rendered(container, container.tagName.toLowerCase()) : elements.element(container);
|
|
37
|
+
}
|
|
38
|
+
scopedRoot();
|
|
39
|
+
return screenDriver({ ...options, root: scopedRoot });
|
|
40
|
+
},
|
|
41
|
+
};
|
|
29
42
|
}
|
|
30
43
|
|
|
31
|
-
function
|
|
44
|
+
function makeScreenActions({ root, pending, tell, act = (action) => action(), timeoutMs = 3000 }: ScreenDriverOptions) {
|
|
32
45
|
const currentRoot = typeof root === "function" ? root : () => root;
|
|
33
46
|
const elements = screenElements(currentRoot);
|
|
34
47
|
function perform(line: string, action: () => void) {
|