Files
cloudflare__vinext/tests/pages-page-handler.test.ts
T
Divanshu Chauhan (divkix) d9a5e63c32 refactor(pages): extract render orchestrator from codegen string (#1784) (#1805)
* refactor(pages): extract render orchestrator from codegen string (#1784)

Move `_renderPage` (~260 lines) and `collectAssetTags` (~85 lines) out
of the generated template string in `entries/pages-server-entry.ts` into
typed, unit-testable server modules:

- `server/pages-page-handler.ts` — `createPagesPageHandler` factory that
  owns the full Pages Router render lifecycle (i18n, route matching,
  404/500 fallback recursion, _next/data envelope, 405 method check,
  ISR cache-key derivation, SSR-context setup). Mirrors how
  `server/app-rsc-handler.ts` is structured relative to
  `entries/app-rsc-entry.ts`.

- `server/pages-asset-tags.ts` — `collectAssetTags` + manifest helpers,
  extracted from the template so they can be unit-tested directly.

- `server/pages-data-route.ts` — adds `normalizePagesDataRequest` so both
  `renderPage` and `runMiddleware` share one implementation instead of
  duplicating the buildId-check logic in the template string.

`entries/pages-server-entry.ts` is now thin wiring: route-table codegen,
embedded config/i18n/buildId, and closures that delegate to the handler.
`renderPage` keeps its exact exported signature; all callers are unaffected.

No behavior change — pure code motion. Fixed a latent bug where the
`isrCacheKey` wrapper in the handler was missing the `buildId` argument on
non-i18n paths (causing a cache-key mismatch); caught by the existing
ISR CSP-nonce test.

* refactor(pages): tighten handler types and improve tests

- Use ComponentType from react for AppComponent, DocumentComponent, and
  PageComponent closures instead of unknown — matches pages-page-response.ts
  which already uses ComponentType. Eliminates the DocumentComponent cast.

- Widen isrCacheKey router param from literal union to string — the literal
  union forced as-casts everywhere it was used indirectly. All call sites
  pass 'pages' or 'app' string literals so the widening is safe.

- Replace the shallow i18n redirect test (which just checked a route miss
  gave 404) with a test that actually exercises the 307 short-circuit:
  visiting / with Accept-Language: fr triggers resolvePagesI18nRequest to
  return redirectUrl and the handler returns 307 to /fr.

- Add second i18n test: locale prefix already present → no redirect.

- Tighten 'allows POST with gSSP' test: assert no Allow header (confirms
  the 405 guard was bypassed, not just that some non-405 came back).
2026-06-07 22:18:12 +01:00

398 lines
15 KiB
TypeScript

/**
* Unit tests for the Pages Router render orchestrator.
*
* Tests the behavior of `createPagesPageHandler` through stub closures,
* verifying route matching, 404/500 fallback, _next/data envelope,
* i18n redirect, 405 method check, and internal-error guard.
*/
import { describe, it, expect, vi } from "vite-plus/test";
import { createPagesPageHandler } from "../packages/vinext/src/server/pages-page-handler.js";
import type { CreatePagesPageHandlerOptions } from "../packages/vinext/src/server/pages-page-handler.js";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function makeRequest(pathname = "/", method = "GET"): Request {
return new Request(`http://localhost${pathname}`, { method });
}
function makePageModule(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return { default: () => null, ...overrides };
}
type PageRoute = {
pattern: string;
patternParts: string[];
isDynamic: boolean;
params: string[];
module: Record<string, unknown>;
filePath: string;
};
function makeRoute(pattern: string, module: Record<string, unknown> = makePageModule()): PageRoute {
return {
pattern,
patternParts: pattern === "/" ? [] : pattern.split("/").filter(Boolean),
isDynamic: pattern.includes(":"),
params: [],
module,
filePath: `/project/pages${pattern === "/" ? "/index" : pattern}.tsx`,
};
}
// Default stubs — most tests override only the pieces they care about.
function makeOpts(
overrides: Partial<CreatePagesPageHandlerOptions> = {},
): CreatePagesPageHandlerOptions {
const pageRoutes: PageRoute[] = overrides.pageRoutes ?? [makeRoute("/")];
return {
pageRoutes,
errorPageRoute: null,
matchRoute: (url, routes) => {
const p = url.split("?")[0];
const route = routes.find((r) => r.pattern === p || r.pattern === p.replace(/\/$/, ""));
return route ? { route, params: {} } : null;
},
i18nConfig: null,
vinextConfig: {
basePath: "",
trailingSlash: false,
disableOptimizedLoading: true,
},
buildId: "test-build-id",
hasMiddleware: false,
appAssetPath: null,
setSSRContext: null,
setI18nContext: null,
wrapWithRouterContext: null,
resetSSRHead: undefined,
getSSRHeadHTML: undefined,
setDocumentInitialHead: undefined,
flushPreloads: undefined,
getFontLinks: () => [],
getFontStyles: () => [],
getFontPreloads: () => [],
renderToReadableStream: async (_element) => {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode("<html><body>page</body></html>"));
controller.close();
},
});
},
renderIsrPassToStringAsync: async (_element) => "<html><body>isr</body></html>",
safeJsonStringify: (v) => JSON.stringify(v),
sanitizeDestination: (d) => d,
createPageElement: (_PageComp, _AppComp, _props) => null,
enhancePageElement: (_PageComp, _AppComp, _props, _opts) => null,
AppComponent: null,
DocumentComponent: null,
...overrides,
};
}
// ---------------------------------------------------------------------------
// Route miss → 404 fallback
// ---------------------------------------------------------------------------
describe("createPagesPageHandler — route miss", () => {
it("returns default 404 when no custom 404 page and no _error page", async () => {
const handler = createPagesPageHandler(makeOpts({ pageRoutes: [] }));
const res = await handler(makeRequest("/missing"), "/missing", null, null, null);
expect(res.status).toBe(404);
const body = await res.text();
expect(body).toContain("This page could not be found");
});
it("renders custom /404 page on route miss", async () => {
const notFoundModule = makePageModule();
const routes = [makeRoute("/404", notFoundModule)];
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: routes,
matchRoute: (url, r) => {
const p = url.split("?")[0];
const route = r.find((rt) => rt.pattern === p);
return route ? { route, params: {} } : null;
},
}),
);
const res = await handler(makeRequest("/nonexistent"), "/nonexistent", null, null, null);
// Custom 404 renders successfully (200 body, 404 status via override)
expect(res.status).toBe(404);
});
it("returns _next/data 404 JSON on data request route miss", async () => {
const handler = createPagesPageHandler(makeOpts({ pageRoutes: [] }));
const res = await handler(makeRequest("/missing"), "/missing", null, null, { isDataReq: true });
expect(res.status).toBe(404);
const ct = res.headers.get("content-type");
expect(ct).toContain("application/json");
});
});
// ---------------------------------------------------------------------------
// Page has no default export
// ---------------------------------------------------------------------------
describe("createPagesPageHandler — no default export", () => {
it("returns 500 when page module has no default export", async () => {
const routes = [makeRoute("/", {})]; // no `default`
const handler = createPagesPageHandler(makeOpts({ pageRoutes: routes }));
const res = await handler(makeRequest("/"), "/", null, null, null);
expect(res.status).toBe(500);
});
});
// ---------------------------------------------------------------------------
// _next/data JSON envelope
// ---------------------------------------------------------------------------
describe("createPagesPageHandler — _next/data", () => {
it("detects /_next/data URL and returns JSON envelope", async () => {
const routes = [makeRoute("/about")];
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: routes,
matchRoute: (url, r) => {
const route = r.find((rt) => rt.pattern === url.split("?")[0]);
return route ? { route, params: {} } : null;
},
}),
);
const dataUrl = "/_next/data/test-build-id/about.json";
const res = await handler(makeRequest(dataUrl), dataUrl, null, null, null);
expect(res.status).toBe(200);
const ct = res.headers.get("content-type");
expect(ct).toContain("application/json");
const body = (await res.json()) as Record<string, unknown>;
expect(body).toHaveProperty("pageProps");
});
it("returns 404 JSON for _next/data with wrong buildId", async () => {
const handler = createPagesPageHandler(makeOpts());
const badUrl = "/_next/data/wrong-build-id/about.json";
const res = await handler(makeRequest(badUrl), badUrl, null, null, null);
expect(res.status).toBe(404);
const ct = res.headers.get("content-type");
expect(ct).toContain("application/json");
});
});
// ---------------------------------------------------------------------------
// 405 method check
// ---------------------------------------------------------------------------
describe("createPagesPageHandler — 405 method check", () => {
it("returns 405 for POST to a static page (no getServerSideProps)", async () => {
const routes = [makeRoute("/about", makePageModule())];
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: routes,
matchRoute: (url, r) => {
const route = r.find((rt) => rt.pattern === url.split("?")[0]);
return route ? { route, params: {} } : null;
},
}),
);
const res = await handler(makeRequest("/about", "POST"), "/about", null, null, null);
expect(res.status).toBe(405);
const allow = res.headers.get("Allow");
expect(allow).toContain("GET");
});
it("skips 405 check when page exports getServerSideProps", async () => {
// The 405 guard only applies to static (no-gSSP) pages. When gSSP is
// present, resolvePagesPageMethodResponse returns null and the render
// pipeline proceeds. Verify by spying on the module method check result.
// We use a module that returns { props: {} } from gSSP so the render
// can complete without hitting renderToReadableStream errors.
const gsspModule = makePageModule({
getServerSideProps: async () => ({ props: {} }),
});
const routes = [makeRoute("/about", gsspModule)];
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: routes,
matchRoute: (url, r) => {
const route = r.find((rt) => rt.pattern === url.split("?")[0]);
return route ? { route, params: {} } : null;
},
}),
);
const res = await handler(makeRequest("/about", "POST"), "/about", null, null, null);
// Must not be 405 — the method check is bypassed for gSSP pages
expect(res.status).not.toBe(405);
// Must not be 405 Allow header either
expect(res.headers.get("Allow")).toBeNull();
});
it("does not 405 on /404 pattern (error pages are exempt)", async () => {
const routes = [makeRoute("/404", makePageModule())];
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: routes,
matchRoute: (url, r) => {
const route = r.find((rt) => rt.pattern === url.split("?")[0]);
return route ? { route, params: {} } : null;
},
}),
);
const res = await handler(makeRequest("/404", "POST"), "/404", null, null, null);
expect(res.status).not.toBe(405);
});
});
// ---------------------------------------------------------------------------
// i18n redirect — 307 short-circuit from resolvePagesI18nRequest
// ---------------------------------------------------------------------------
describe("createPagesPageHandler — i18n redirect", () => {
// getLocaleRedirect fires when pathname === "/" and the Accept-Language
// header prefers a non-default locale. The handler must return a 307
// before attempting any route match.
it("returns 307 when i18n locale detection produces a redirect", async () => {
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: [makeRoute("/")],
i18nConfig: {
locales: ["en", "fr"],
defaultLocale: "en",
},
}),
);
// Visit / with Accept-Language: fr — resolvePagesI18nRequest redirects to /fr
const req = new Request("http://localhost/", {
headers: { "accept-language": "fr" },
});
const res = await handler(req, "/", null, null, null);
expect(res.status).toBe(307);
expect(res.headers.get("location")).toContain("/fr");
});
it("does not redirect when locale prefix is already present", async () => {
const routes = [makeRoute("/fr/about")];
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: routes,
i18nConfig: {
locales: ["en", "fr"],
defaultLocale: "en",
},
matchRoute: (url, r) => {
const route = r.find((rt) => rt.pattern === url.split("?")[0]);
return route ? { route, params: {} } : null;
},
}),
);
const res = await handler(makeRequest("/fr/about"), "/fr/about", null, null, null);
// Not a 307 — the locale prefix is already present
expect(res.status).not.toBe(307);
});
});
// ---------------------------------------------------------------------------
// Internal error guard (prevents infinite recursion on error pages)
// ---------------------------------------------------------------------------
describe("createPagesPageHandler — internal error guard", () => {
it("returns 500 text when __isInternalErrorRender is set and render throws", async () => {
const errorRoute = makeRoute("/_error", makePageModule());
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: [errorRoute],
errorPageRoute: errorRoute,
matchRoute: (url, r) => {
const route = r.find((rt) => rt.pattern === url.split("?")[0]);
return route ? { route, params: {} } : null;
},
// Cause an error during render
renderToReadableStream: async () => {
throw new Error("render failure");
},
}),
);
const res = await handler(makeRequest("/_error"), "/_error", null, null, {
__isInternalErrorRender: true,
__forcedRoute: errorRoute,
});
expect(res.status).toBe(500);
const body = await res.text();
expect(body).toBe("Internal Server Error");
});
it("falls back to 500 text on data request even without __isInternalErrorRender", async () => {
// Data requests skip renderToReadableStream (JSON envelope path), so we
// need to throw earlier — in createPageElement, which is called inside
// resolvePagesPageData to build the element for ISR/SSR rendering.
const routes = [
makeRoute("/about", {
...makePageModule(),
getStaticProps: async () => {
throw new Error("gssp failure");
},
}),
];
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: routes,
matchRoute: (url, r) => {
const route = r.find((rt) => rt.pattern === url.split("?")[0]);
return route ? { route, params: {} } : null;
},
// getFontPreloads is called before the isDataReq branch.
// Throwing here triggers the catch block regardless of isDataReq.
getFontPreloads: () => {
throw new Error("font failure");
},
}),
);
// isDataReq=true → no error-page recursion, direct 500
const res = await handler(makeRequest("/about"), "/about", null, null, { isDataReq: true });
expect(res.status).toBe(500);
});
});
// ---------------------------------------------------------------------------
// renderErrorPageOnMiss: false — no 404 recursion
// ---------------------------------------------------------------------------
describe("createPagesPageHandler — renderErrorPageOnMiss: false", () => {
it("returns default 404 without recursing when renderErrorPageOnMiss=false", async () => {
const handler = createPagesPageHandler(makeOpts({ pageRoutes: [] }));
const res = await handler(makeRequest("/missing"), "/missing", null, null, {
renderErrorPageOnMiss: false,
});
expect(res.status).toBe(404);
const body = await res.text();
expect(body).toContain("This page could not be found");
});
});
// ---------------------------------------------------------------------------
// setSSRContext called
// ---------------------------------------------------------------------------
describe("createPagesPageHandler — SSR context", () => {
it("calls setSSRContext with the matched route pattern", async () => {
const setSSRContext = vi.fn();
const routes = [makeRoute("/about")];
const handler = createPagesPageHandler(
makeOpts({
pageRoutes: routes,
setSSRContext,
matchRoute: (url, r) => {
const route = r.find((rt) => rt.pattern === url.split("?")[0]);
return route ? { route, params: {} } : null;
},
}),
);
await handler(makeRequest("/about"), "/about", null, null, null);
expect(setSSRContext).toHaveBeenCalled();
const ctx = setSSRContext.mock.calls[0][0] as Record<string, unknown>;
expect(ctx.pathname).toBe("/about");
});
});