Skip to content

Commit 1b9f266

Browse files
committed
fix(testing): apply review findings — runMiddleware stateCookieName, runLoaderResult.result, parity/snapshot robustness, T8 reverse typing
From the multi-agent review of the @rangojs/router/testing surface (+ external T8): - runMiddleware now returns `stateCookieName` (parity with runInRequestContext / runLoaderResult / renderHandler; it accepted `stateCookie` but never surfaced the resolved name). +3 tests (invalidate/keep/seed). - runLoaderResult envelope field `data` -> `result`, matching runInRequestContext's envelope (the two snapshot primitives now agree). Tests + docs updated. - expectParity: snapshot() gains `.first()` + `.catch(()=>null)` (parity with readObserved — no unhandled rejection on a missing testid); settleSubmit warns (instead of silently snapshotting) when the observed state never stabilizes. - T8: createTestRequestContext().ctx.reverse is typed via the new TestRequestContextObject so reversing a LOCAL routeMap name type-checks (was typed against the global Rango.GeneratedRouteMap, forcing a cast). +1 test. - dispatch: +_rsc_action redirect-interception test (204 + X-RSC-Redirect). - render-route: +handles-persist-across-navigate, +locale-mount (include('/:locale?')) tests. cache-status: route-name keys + a mixed-stream filterCacheDecisions test. installed-vitest-config: assert the bare @rangojs/router -> index.rsc.ts alias. headersToObject stays duplicated between render-handler (flight tier) and internal/context (node tier) on purpose — context.ts is not react-server-safe (why seed-vars was split out); documented in-code.
1 parent 8bccbdf commit 1b9f266

13 files changed

Lines changed: 331 additions & 51 deletions

‎packages/rangojs-router/src/__tests__/installed-vitest-config.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,19 @@ if (cfg.alias.length !== 5) throw new Error("expected 5 aliases, got " + cfg.ali
7878
if (!cfg.server.deps.inline.length) throw new Error("missing server.deps.inline");
7979
if (!cfg.alias.every((a) => existsSync(a.replacement)))
8080
throw new Error("alias targets do not resolve to shipped src files");
81+
// The load-bearing alias: bare @rangojs/router -> its react-server build, so a
82+
// handler/component reading getRequestContext()/cookies() resolves the real impl
83+
// (not the throwing out-of-react-server stub). resolve.conditions alone does not
84+
// reliably do this for bare-package export resolution, so this alias MUST exist.
85+
const bareToRsc = cfg.alias.some((a) => {
86+
const m =
87+
a.find instanceof RegExp
88+
? a.find.test("@rangojs/router")
89+
: a.find === "@rangojs/router";
90+
return m && a.replacement.endsWith("index.rsc.ts");
91+
});
92+
if (!bareToRsc)
93+
throw new Error("bare @rangojs/router must alias to index.rsc.ts");
8194
console.log("QUICKSTART_OK");
8295
`,
8396
);

‎packages/rangojs-router/src/testing/__tests__/cache-status.test.ts‎

Lines changed: 74 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,28 +18,32 @@ describe("parseCacheHeader", () => {
1818
});
1919

2020
it("parses a single entry", () => {
21-
expect(parseCacheHeader("/products/:id=hit")).toEqual({
22-
"/products/:id": "hit",
21+
expect(parseCacheHeader("product.detail=hit")).toEqual({
22+
"product.detail": "hit",
2323
});
2424
});
2525

2626
it("parses multiple comma-separated entries", () => {
27-
expect(parseCacheHeader("/a=hit, /b=stale, /c=miss")).toEqual({
28-
"/a": "hit",
29-
"/b": "stale",
30-
"/c": "miss",
27+
expect(
28+
parseCacheHeader("route.a=hit, route.b=stale, route.c=miss"),
29+
).toEqual({
30+
"route.a": "hit",
31+
"route.b": "stale",
32+
"route.c": "miss",
3133
});
3234
});
3335

3436
it("tolerates surrounding whitespace and trailing commas", () => {
35-
expect(parseCacheHeader(" /a = hit , /b=miss ,")).toEqual({
36-
"/a": "hit",
37-
"/b": "miss",
37+
expect(parseCacheHeader(" route.a = hit , route.b=miss ,")).toEqual({
38+
"route.a": "hit",
39+
"route.b": "miss",
3840
});
3941
});
4042

4143
it("ignores malformed entries without a status", () => {
42-
expect(parseCacheHeader("/a, /b=hit, =miss")).toEqual({ "/b": "hit" });
44+
expect(parseCacheHeader("route.a, route.b=hit, =miss")).toEqual({
45+
"route.b": "hit",
46+
});
4347
});
4448
});
4549

@@ -51,40 +55,46 @@ describe("assertCacheStatus", () => {
5155
}
5256

5357
it("passes when the segment matches the expected status", () => {
54-
const res = responseWith("/products/:id=hit");
55-
expect(() => assertCacheStatus(res, "/products/:id", "hit")).not.toThrow();
58+
const res = responseWith("product.detail=hit");
59+
expect(() => assertCacheStatus(res, "product.detail", "hit")).not.toThrow();
5660
});
5761

5862
it("works against a plain { headers } target", () => {
59-
const target = { headers: new Headers({ "X-Rango-Cache": "/x=stale" }) };
60-
expect(() => assertCacheStatus(target, "/x", "stale")).not.toThrow();
63+
const target = {
64+
headers: new Headers({ "X-Rango-Cache": "route.x=stale" }),
65+
};
66+
expect(() => assertCacheStatus(target, "route.x", "stale")).not.toThrow();
6167
});
6268

6369
it("throws when the status differs", () => {
64-
const res = responseWith("/products/:id=miss");
65-
expect(() => assertCacheStatus(res, "/products/:id", "hit")).toThrow(
70+
const res = responseWith("product.detail=miss");
71+
expect(() => assertCacheStatus(res, "product.detail", "hit")).toThrow(
6672
/expected "hit" but got "miss"/,
6773
);
6874
});
6975

7076
it("throws when the segment is absent", () => {
71-
const res = responseWith("/other=hit");
72-
expect(() => assertCacheStatus(res, "/products/:id", "hit")).toThrow(
77+
const res = responseWith("route.other=hit");
78+
expect(() => assertCacheStatus(res, "product.detail", "hit")).toThrow(
7379
/not found in X-Rango-Cache/,
7480
);
7581
});
7682

7783
it("throws a clear error when the header is missing (gate off)", () => {
7884
const res = new Response(null);
79-
expect(() => assertCacheStatus(res, "/a", "hit")).toThrow(
85+
expect(() => assertCacheStatus(res, "route.a", "hit")).toThrow(
8086
/no X-Rango-Cache header/,
8187
);
8288
});
8389

8490
it("distinguishes prerendered and passthrough statuses", () => {
85-
const res = responseWith("/a=prerendered, /b=passthrough");
86-
expect(() => assertCacheStatus(res, "/a", "prerendered")).not.toThrow();
87-
expect(() => assertCacheStatus(res, "/b", "passthrough")).not.toThrow();
91+
const res = responseWith("route.a=prerendered, route.b=passthrough");
92+
expect(() =>
93+
assertCacheStatus(res, "route.a", "prerendered"),
94+
).not.toThrow();
95+
expect(() =>
96+
assertCacheStatus(res, "route.b", "passthrough"),
97+
).not.toThrow();
8898
});
8999
});
90100

@@ -175,4 +185,46 @@ describe("createCacheSink (telemetry capture path)", () => {
175185
expect(decision.segments?.[0].cacheStatus).toBe("stale");
176186
expect(decision.segments?.[0].shouldRevalidate).toBe(true);
177187
});
188+
189+
it("filters cache.decision out of a mixed event stream and exposes per-decision segment status", () => {
190+
// The full sink workflow a consumer runs: capture a mixed stream, filter to
191+
// the cache decisions, then assert each decision's segment-level status.
192+
const { sink, events } = createCacheSink();
193+
sink.emit({
194+
type: "request.start",
195+
timestamp: 1,
196+
method: "GET",
197+
pathname: "/x",
198+
transaction: "match",
199+
isPartial: false,
200+
});
201+
sink.emit({
202+
type: "cache.decision",
203+
timestamp: 2,
204+
pathname: "/x",
205+
routeKey: "/x",
206+
hit: true,
207+
shouldRevalidate: false,
208+
source: "runtime",
209+
segments: [{ id: "/x", type: "route", cacheStatus: "hit" }],
210+
});
211+
sink.emit({
212+
type: "cache.decision",
213+
timestamp: 3,
214+
pathname: "/y",
215+
routeKey: "/y",
216+
hit: false,
217+
shouldRevalidate: false,
218+
source: "runtime",
219+
segments: [{ id: "/y", type: "route", cacheStatus: "miss" }],
220+
});
221+
222+
const decisions = filterCacheDecisions(events);
223+
// request.start is filtered out; both cache.decision events remain, in order.
224+
expect(decisions).toHaveLength(2);
225+
expect(decisions.map((d) => d.segments?.[0].cacheStatus)).toEqual([
226+
"hit",
227+
"miss",
228+
]);
229+
});
178230
});

‎packages/rangojs-router/src/testing/__tests__/dispatch.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -828,6 +828,29 @@ describe("dispatch", () => {
828828
expect(res.headers.get("Location")).toBeNull();
829829
});
830830

831+
it("converts a middleware 302 on a _rsc_action request to 204 + X-RSC-Redirect", async () => {
832+
// interceptRedirectForPartial runs on partial AND action requests alike, so
833+
// a middleware redirect on an action request (?_rsc_action=1) must also
834+
// become a 204 + X-RSC-Redirect (dispatch does not execute the action
835+
// itself, but the global middleware chain still runs and can redirect).
836+
const redirectMw: MiddlewareFn = async () =>
837+
new Response(null, { status: 302, headers: { Location: "/login" } });
838+
const router = createRouter<{}>({})
839+
.use(redirectMw)
840+
.routes(
841+
urls(({ path }) => [
842+
path.json("/api/data", () => ({ ok: true }), { name: "api.data" }),
843+
]),
844+
) as any;
845+
846+
const res = await dispatch(router, {
847+
request: "/api/data?_rsc_action=1",
848+
});
849+
expect(res.status).toBe(204);
850+
expect(res.headers.get("X-RSC-Redirect")).toBe("/login");
851+
expect(res.headers.get("Location")).toBeNull();
852+
});
853+
831854
it("fires ctx.onResponse() when global middleware short-circuits", async () => {
832855
// Production drains onResponse via finalizeResponse on every global-chain
833856
// exit (handler.ts:499-501). A middleware that registers an onResponse

‎packages/rangojs-router/src/testing/__tests__/render-route.test.tsx‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,34 @@ describe("renderRoute handles seeding runs the real collect", () => {
4848
expect(getByTestId("title").textContent).toBe("C");
4949
});
5050
});
51+
52+
it("keeps seeded handles resolvable across router.navigate() (#20)", async () => {
53+
// Handles are seeded once at initial render and persist across navigate()
54+
// within the test (like loaderData) — unlike a real navigation, which would
55+
// re-run handlers. Pin that a handle still resolves after navigate().
56+
const Crumbs = createHandle<string, string>((segments) =>
57+
segments.flat().join(" > "),
58+
);
59+
function View() {
60+
const { id } = useParams<{ id: string }>();
61+
return (
62+
<div>
63+
<span data-testid="id">{id}</span>
64+
<span data-testid="crumbs">{useHandle(Crumbs)}</span>
65+
</div>
66+
);
67+
}
68+
const { getByTestId, router } = await renderRoute(
69+
[{ path: "/users/:id", Component: View }],
70+
{ request: "/users/alice", handles: [[Crumbs, ["Home", "Users"]]] },
71+
);
72+
expect(getByTestId("crumbs").textContent).toBe("Home > Users");
73+
74+
await router.navigate("/users/bob");
75+
76+
expect(getByTestId("id").textContent).toBe("bob");
77+
expect(getByTestId("crumbs").textContent).toBe("Home > Users");
78+
});
5179
});
5280

5381
describe("renderRoute", () => {
@@ -280,6 +308,33 @@ describe("renderRoute mount (include() scope)", () => {
280308
);
281309
expect(getByTestId("mount").textContent).toBe("/shop");
282310
});
311+
312+
it("models a locale-parameterized include (mount = a resolved /:locale? value) (#25)", async () => {
313+
// include('/:locale?', subApp) mounts the sub-app under a RESOLVED locale
314+
// prefix (e.g. "/en"). Seeding mount: "/en" reproduces that: useReverse /
315+
// useHref inside the sub-app prefix by the locale, so a reversed link keeps
316+
// it — the locale-prefixed-routes pattern, end to end.
317+
function LocalePage() {
318+
const reverse = useReverse({ product: "/c/:slug" });
319+
const href = useHref();
320+
return (
321+
<div>
322+
<span data-testid="mount">{useMount()}</span>
323+
<a data-testid="rev" href={reverse("product", { slug: "wine" })}>
324+
x
325+
</a>
326+
<span data-testid="href">{href("/c/wine")}</span>
327+
</div>
328+
);
329+
}
330+
const { getByTestId } = await renderRoute(
331+
[{ path: "/c/:slug", Component: LocalePage }],
332+
{ mount: "/en", request: "/c/wine" },
333+
);
334+
expect(getByTestId("mount").textContent).toBe("/en");
335+
expect(getByTestId("rev").getAttribute("href")).toBe("/en/c/wine");
336+
expect(getByTestId("href").textContent).toBe("/en/c/wine");
337+
});
283338
});
284339

285340
describe("renderRoute reverse + optional params from the match", () => {

‎packages/rangojs-router/src/testing/__tests__/run-in-request-context.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,4 +324,15 @@ describe("runWithRequestContext re-export", () => {
324324
);
325325
expect(sid).toBe("zzz");
326326
});
327+
328+
it("ctx.reverse accepts a local routeMap name without a cast (T8)", () => {
329+
// The returned ctx.reverse is typed (TestRequestContextObject) against the
330+
// routeMap you pass, NOT the global Rango.GeneratedRouteMap — so reversing a
331+
// test-only route name type-checks (pre-T8 it errored and forced a cast).
332+
// This call compiling is itself the assertion; the value confirms runtime.
333+
const { ctx } = createTestRequestContext({
334+
routeMap: { "test-only": "/t/:id" },
335+
});
336+
expect(ctx.reverse("test-only", { id: "9" })).toBe("/t/9");
337+
});
327338
});

‎packages/rangojs-router/src/testing/__tests__/run-loader.test.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -360,24 +360,24 @@ describe("runLoader accepts a registered createLoader handle", () => {
360360
});
361361

362362
describe("runLoaderResult — effect observability (cookies/headers/redirect)", () => {
363-
it("returns data and undefined thrown when the loader returns normally", async () => {
364-
const { data, thrown } = await runLoaderResult(async () => ({
363+
it("returns result and undefined thrown when the loader returns normally", async () => {
364+
const { result, thrown } = await runLoaderResult(async () => ({
365365
items: [1, 2, 3],
366366
}));
367-
expect(data).toEqual({ items: [1, 2, 3] });
367+
expect(result).toEqual({ items: [1, 2, 3] });
368368
expect(thrown).toBeUndefined();
369369
});
370370

371371
it("surfaces a Set-Cookie a loader set on response + cookies", async () => {
372372
const {
373-
data,
373+
result,
374374
response,
375375
cookies: jar,
376376
} = await runLoaderResult(async () => {
377377
cookies().set("prefs", "dark", { path: "/" });
378378
return { ok: true };
379379
});
380-
expect(data).toEqual({ ok: true });
380+
expect(result).toEqual({ ok: true });
381381
expect(jar.prefs).toBe("dark");
382382
expect(
383383
response.headers.getSetCookie().some((c) => c.startsWith("prefs=dark")),
@@ -388,7 +388,7 @@ describe("runLoaderResult — effect observability (cookies/headers/redirect)",
388388
// The exact gap the finding documents: today runLoader only lets you check
389389
// the redirect, not the Set-Cookie. runLoaderResult exposes BOTH.
390390
const {
391-
data,
391+
result,
392392
thrown,
393393
response,
394394
cookies: jar,
@@ -399,7 +399,7 @@ describe("runLoaderResult — effect observability (cookies/headers/redirect)",
399399
},
400400
{ request: new Request("https://app.test/login?token=ok") },
401401
);
402-
expect(data).toBeUndefined();
402+
expect(result).toBeUndefined();
403403
expect(thrown).toBeInstanceOf(Response);
404404
expect((thrown as Response).headers.get("Location")).toBe("/");
405405
// response merges the redirect's Location AND the accumulated Set-Cookie.
@@ -425,10 +425,10 @@ describe("runLoaderResult — effect observability (cookies/headers/redirect)",
425425

426426
it("preserves the full loader context (params, ctx.use seeding) on the rich path", async () => {
427427
const Other = createVar<{ n: number }>();
428-
const { data } = await runLoaderResult(
428+
const { result } = await runLoaderResult(
429429
async (ctx) => ({ id: ctx.params.id, n: ctx.get(Other)?.n }),
430430
{ params: { id: "7" }, vars: [[Other, { n: 5 }]] },
431431
);
432-
expect(data).toEqual({ id: "7", n: 5 });
432+
expect(result).toEqual({ id: "7", n: 5 });
433433
});
434434
});

0 commit comments

Comments
 (0)