chore: speed up tests (#1791)

This PR speeds up tests by handling custom created `Requests` object
directly instead of binding a socket and making a real HTTP request. For
most tests this is fine, and for those that aren't the existing testing
methods are all preserved.
This commit is contained in:
Marvin Hagemeister
2023-09-18 18:44:22 +02:00
committed by GitHub
parent c76f15479f
commit 3850131063
12 changed files with 247 additions and 158 deletions
+7 -3
View File
@@ -91,6 +91,11 @@ interface StaticFile {
etag: string; etag: string;
} }
export type FromManifestOptions = FreshOptions & {
skipSnapshot?: boolean;
dev?: boolean;
};
export class ServerContext { export class ServerContext {
#dev: boolean; #dev: boolean;
#routes: Route[]; #routes: Route[];
@@ -149,7 +154,7 @@ export class ServerContext {
*/ */
static async fromManifest( static async fromManifest(
manifest: Manifest, manifest: Manifest,
opts: FreshOptions & { skipSnapshot?: boolean; dev?: boolean }, opts: FromManifestOptions,
): Promise<ServerContext> { ): Promise<ServerContext> {
const dev = Deno.env.get("__FRSH_LEGACY_DEV") === "true" || const dev = Deno.env.get("__FRSH_LEGACY_DEV") === "true" ||
Boolean(opts.dev); Boolean(opts.dev);
@@ -907,9 +912,8 @@ export class ServerContext {
"%cAn error occurred during route handling or page rendering.", "%cAn error occurred during route handling or page rendering.",
"color:red", "color:red",
); );
let codeFrame: string | undefined = undefined;
if (this.#dev && error instanceof Error) { if (this.#dev && error instanceof Error) {
codeFrame = await getCodeFrame(error); const codeFrame = await getCodeFrame(error);
if (codeFrame) { if (codeFrame) {
console.error(); console.error();
+1
View File
@@ -1,6 +1,7 @@
import { LayoutConfig } from "$fresh/server.ts"; import { LayoutConfig } from "$fresh/server.ts";
import { ComponentChildren } from "preact"; import { ComponentChildren } from "preact";
import { ServerContext } from "./context.ts"; import { ServerContext } from "./context.ts";
export type { FromManifestOptions } from "./context.ts";
export { Status } from "./deps.ts"; export { Status } from "./deps.ts";
import { import {
ErrorHandler, ErrorHandler,
+1
View File
@@ -33,6 +33,7 @@ export { defineConfig, type Preset } from "https://esm.sh/@twind/core@1.1.3";
export { default as presetTailwind } from "https://esm.sh/@twind/preset-tailwind@1.1.4"; export { default as presetTailwind } from "https://esm.sh/@twind/preset-tailwind@1.1.4";
export * as fs from "https://deno.land/std@0.195.0/fs/mod.ts"; export * as fs from "https://deno.land/std@0.195.0/fs/mod.ts";
export { export {
basename,
dirname, dirname,
fromFileUrl, fromFileUrl,
join, join,
+10 -9
View File
@@ -7,6 +7,7 @@ import {
assertTextMatch, assertTextMatch,
fetchHtml, fetchHtml,
waitForStyle, waitForStyle,
withFakeServe,
withFresh, withFresh,
withPageName, withPageName,
} from "./test_utils.ts"; } from "./test_utils.ts";
@@ -38,11 +39,11 @@ Deno.test({
}); });
Deno.test("adds refresh script to html", async () => { Deno.test("adds refresh script to html", async () => {
await withFresh("./tests/fixture/dev.ts", async (address) => { await withFakeServe("./tests/fixture/dev.ts", async (server) => {
const doc = await fetchHtml(address); const doc = await server.getHtml("/");
assertSelector(doc, `script[src="/_frsh/refresh.js"]`); assertSelector(doc, `script[src="/_frsh/refresh.js"]`);
const res = await fetch(`${address}/_frsh/refresh.js`); const res = await server.get(`/_frsh/refresh.js`);
assertEquals( assertEquals(
res.headers.get("content-type"), res.headers.get("content-type"),
"application/javascript; charset=utf-8", "application/javascript; charset=utf-8",
@@ -72,30 +73,30 @@ Deno.test("preact/debug is active in dev mode", async () => {
}); });
Deno.test("middleware destination internal", async () => { Deno.test("middleware destination internal", async () => {
await withFresh("./tests/fixture/dev.ts", async (address) => { await withFakeServe("./tests/fixture/dev.ts", async (server) => {
const resp = await fetch(`${address}/_frsh/refresh.js`); const resp = await server.get(`/_frsh/refresh.js`);
assertEquals(resp.headers.get("destination"), "internal"); assertEquals(resp.headers.get("destination"), "internal");
await resp.body?.cancel(); await resp.body?.cancel();
}); });
}); });
Deno.test("warns when using hooks in server components", async (t) => { Deno.test("warns when using hooks in server components", async (t) => {
await withFresh("./tests/fixture/main.ts", async (address) => { await withFakeServe("./tests/fixture/main.ts", async (server) => {
await t.step("useState", async () => { await t.step("useState", async () => {
const doc = await fetchHtml(`${address}/hooks-server/useState`); const doc = await server.getHtml(`/hooks-server/useState`);
assertTextMatch(doc, "p", /Hook "useState" cannot be used/); assertTextMatch(doc, "p", /Hook "useState" cannot be used/);
// Check for hint // Check for hint
assertTextMatch(doc, "p", /Instead, use the "useSignal" hook/); assertTextMatch(doc, "p", /Instead, use the "useSignal" hook/);
}); });
await t.step("useReducer", async () => { await t.step("useReducer", async () => {
const doc = await fetchHtml(`${address}/hooks-server/useReducer`); const doc = await server.getHtml(`/hooks-server/useReducer`);
assertTextMatch(doc, "p", /Hook "useReducer" cannot be used/); assertTextMatch(doc, "p", /Hook "useReducer" cannot be used/);
}); });
// Valid // Valid
await t.step("does not warn in island", async () => { await t.step("does not warn in island", async () => {
const doc = await fetchHtml(`${address}/hooks-server/island`); const doc = await server.getHtml(`/hooks-server/island`);
assertTextMany(doc, "p", ["0"]); assertTextMany(doc, "p", ["0"]);
}); });
}); });
+16 -17
View File
@@ -2,16 +2,15 @@ import {
assertNotSelector, assertNotSelector,
assertSelector, assertSelector,
assertTextMany, assertTextMany,
fetchHtml, withFakeServe,
withFresh,
} from "$fresh/tests/test_utils.ts"; } from "$fresh/tests/test_utils.ts";
import { assertNotMatch } from "$std/testing/asserts.ts"; import { assertNotMatch } from "$std/testing/asserts.ts";
Deno.test("doesn't apply internal app template", async () => { Deno.test("doesn't apply internal app template", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_explicit_app/main.ts", "./tests/fixture_explicit_app/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}`); const doc = await server.getHtml(`/`);
// Doesn't render internal app template // Doesn't render internal app template
assertNotSelector(doc, "body body"); assertNotSelector(doc, "body body");
@@ -32,10 +31,10 @@ Deno.test("doesn't apply internal app template", async () => {
}); });
Deno.test("user _app works with <Head>", async () => { Deno.test("user _app works with <Head>", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_explicit_app/main.ts", "./tests/fixture_explicit_app/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/head`); const doc = await server.getHtml(`/head`);
// Doesn't render internal app template // Doesn't render internal app template
assertNotSelector(doc, "body body"); assertNotSelector(doc, "body body");
@@ -59,20 +58,20 @@ Deno.test("user _app works with <Head>", async () => {
}); });
Deno.test("don't duplicate <title>", async () => { Deno.test("don't duplicate <title>", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_explicit_app/main.ts", "./tests/fixture_explicit_app/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/title`); const doc = await server.getHtml(`/title`);
assertTextMany(doc, "title", ["foo bar"]); assertTextMany(doc, "title", ["foo bar"]);
}, },
); );
}); });
Deno.test("sets <html> + <head> + <body> classes", async () => { Deno.test("sets <html> + <head> + <body> classes", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_explicit_app/main.ts", "./tests/fixture_explicit_app/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}`); const doc = await server.getHtml(``);
assertSelector(doc, "html.html"); assertSelector(doc, "html.html");
assertSelector(doc, "head.head"); assertSelector(doc, "head.head");
assertSelector(doc, "body.body"); assertSelector(doc, "body.body");
@@ -82,10 +81,10 @@ Deno.test("sets <html> + <head> + <body> classes", async () => {
// Issue: https://github.com/denoland/fresh/issues/1666 // Issue: https://github.com/denoland/fresh/issues/1666
Deno.test("renders valid html document", async () => { Deno.test("renders valid html document", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_explicit_app/main.ts", "./tests/fixture_explicit_app/main.ts",
async (address) => { async (server) => {
const res = await fetch(address); const res = await server.get("/");
const text = await res.text(); const text = await res.text();
assertNotMatch(text, /<\/body><\/head>/); assertNotMatch(text, /<\/body><\/head>/);
+6 -7
View File
@@ -10,9 +10,8 @@ import {
assertSelector, assertSelector,
assertTextMatch, assertTextMatch,
clickWhenListenerReady, clickWhenListenerReady,
fetchHtml,
waitForText, waitForText,
withFresh, withFakeServe,
withPageName, withPageName,
} from "./test_utils.ts"; } from "./test_utils.ts";
@@ -503,21 +502,21 @@ Deno.test({
}); });
Deno.test("throws when passing non-jsx children to an island", async (t) => { Deno.test("throws when passing non-jsx children to an island", async (t) => {
await withFresh( await withFakeServe(
"./tests/fixture_island_nesting/dev.ts", "./tests/fixture_island_nesting/dev.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/island_invalid_children`); const doc = await server.getHtml(`/island_invalid_children`);
assertSelector(doc, ".frsh-error-page"); assertSelector(doc, ".frsh-error-page");
assertTextMatch(doc, "pre", /Invalid JSX child passed to island/); assertTextMatch(doc, "pre", /Invalid JSX child passed to island/);
const doc2 = await fetchHtml(`${address}/island_invalid_children_fn`); const doc2 = await server.getHtml(`/island_invalid_children_fn`);
assertSelector(doc2, ".frsh-error-page"); assertSelector(doc2, ".frsh-error-page");
assertTextMatch(doc2, "pre", /Invalid JSX child passed to island/); assertTextMatch(doc2, "pre", /Invalid JSX child passed to island/);
await t.step("should not throw on valid children", async () => { await t.step("should not throw on valid children", async () => {
const doc2 = await fetchHtml(`${address}/island_valid_children`); const doc2 = await server.getHtml(`/island_valid_children`);
assertNotSelector(doc2, ".frsh-error-page"); assertNotSelector(doc2, ".frsh-error-page");
}); });
+50 -54
View File
@@ -3,70 +3,69 @@ import {
assertNotSelector, assertNotSelector,
assertSelector, assertSelector,
clickWhenListenerReady, clickWhenListenerReady,
fetchHtml,
waitForText, waitForText,
withFresh, withFakeServe,
withPageName, withPageName,
} from "./test_utils.ts"; } from "./test_utils.ts";
Deno.test("apply root _layout and _app", async () => { Deno.test("apply root _layout and _app", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(address); const doc = await server.getHtml("/");
assert(doc.body.textContent?.includes("it works")); assert(doc.body.textContent?.includes("it works"));
assertSelector(doc, ".app .root-layout .home-page"); assertSelector(doc, ".app .root-layout .home-page");
const doc2 = await fetchHtml(`${address}/other`); const doc2 = await server.getHtml("/other");
assertSelector(doc2, ".app .root-layout .other-page"); assertSelector(doc2, ".app .root-layout .other-page");
}, },
); );
}); });
Deno.test("apply sub layouts", async () => { Deno.test("apply sub layouts", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/foo`); const doc = await server.getHtml("/foo");
assertSelector(doc, ".app .root-layout .foo-layout .foo-page"); assertSelector(doc, ".app .root-layout .foo-layout .foo-page");
const doc2 = await fetchHtml(`${address}/foo/bar`); const doc2 = await server.getHtml("/foo/bar");
assertSelector(doc2, ".app .root-layout .foo-layout .bar-page"); assertSelector(doc2, ".app .root-layout .foo-layout .bar-page");
}, },
); );
}); });
Deno.test("skip layouts if not present", async () => { Deno.test("skip layouts if not present", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/skip/sub`); const doc = await server.getHtml(`/skip/sub`);
assertSelector(doc, ".app .root-layout .sub-layout .sub-page"); assertSelector(doc, ".app .root-layout .sub-layout .sub-page");
}, },
); );
}); });
Deno.test("check file types", async (t) => { Deno.test("check file types", async (t) => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
await t.step(".js", async () => { await t.step(".js", async () => {
const doc = await fetchHtml(`${address}/files/js`); const doc = await server.getHtml(`/files/js`);
assertSelector(doc, ".app .root-layout .js-layout .js-page"); assertSelector(doc, ".app .root-layout .js-layout .js-page");
}); });
await t.step(".jsx", async () => { await t.step(".jsx", async () => {
const doc = await fetchHtml(`${address}/files/jsx`); const doc = await server.getHtml(`/files/jsx`);
assertSelector(doc, ".app .root-layout .jsx-layout .jsx-page"); assertSelector(doc, ".app .root-layout .jsx-layout .jsx-page");
}); });
await t.step(".ts", async () => { await t.step(".ts", async () => {
const doc = await fetchHtml(`${address}/files/ts`); const doc = await server.getHtml(`/files/ts`);
assertSelector(doc, ".app .root-layout .ts-layout .ts-page"); assertSelector(doc, ".app .root-layout .ts-layout .ts-page");
}); });
await t.step(".tsx", async () => { await t.step(".tsx", async () => {
const doc = await fetchHtml(`${address}/files/tsx`); const doc = await server.getHtml(`/files/tsx`);
assertSelector(doc, ".app .root-layout .tsx-layout .tsx-page"); assertSelector(doc, ".app .root-layout .tsx-layout .tsx-page");
}); });
}, },
@@ -74,20 +73,20 @@ Deno.test("check file types", async (t) => {
}); });
Deno.test("render async layout", async () => { Deno.test("render async layout", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/async`); const doc = await server.getHtml(`/async`);
assertSelector(doc, ".app .root-layout .async-layout .async-page"); assertSelector(doc, ".app .root-layout .async-layout .async-page");
}, },
); );
}); });
Deno.test("render nested async layout", async () => { Deno.test("render nested async layout", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/async/sub`); const doc = await server.getHtml(`/async/sub`);
assertSelector( assertSelector(
doc, doc,
".app .root-layout .async-layout .async-sub-layout .async-sub-page", ".app .root-layout .async-layout .async-sub-layout .async-sub-page",
@@ -96,27 +95,24 @@ Deno.test("render nested async layout", async () => {
); );
}); });
Deno.test({ Deno.test("can return Response from async layout", async () => {
name: "can return Response from async layout", await withFakeServe(
fn: async () => { "./tests/fixture_layouts/main.ts",
await withFresh( async (server) => {
"./tests/fixture_layouts/main.ts", const doc = await server.getHtml(`/async/redirect`);
async (address) => { assertSelector(
const doc = await fetchHtml(`${address}/async/redirect`); doc,
assertSelector( ".app .root-layout .async-layout .async-sub-layout .async-sub-page",
doc, );
".app .root-layout .async-layout .async-sub-layout .async-sub-page", },
); );
},
);
},
}); });
Deno.test("disable _app layout", async () => { Deno.test("disable _app layout", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/override/no_app`); const doc = await server.getHtml(`/override/no_app`);
assertNotSelector(doc, "body body"); assertNotSelector(doc, "body body");
assertSelector(doc, "body > .override-layout >.no-app"); assertSelector(doc, "body > .override-layout >.no-app");
}, },
@@ -124,10 +120,10 @@ Deno.test("disable _app layout", async () => {
}); });
Deno.test("disable _app in _layout", async () => { Deno.test("disable _app in _layout", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/override/layout_no_app`); const doc = await server.getHtml(`/override/layout_no_app`);
assertNotSelector(doc, "body body"); assertNotSelector(doc, "body body");
assertSelector(doc, "body > .override-layout > .no-app-layout > .page"); assertSelector(doc, "body > .override-layout > .no-app-layout > .page");
}, },
@@ -135,30 +131,30 @@ Deno.test("disable _app in _layout", async () => {
}); });
Deno.test("override layouts", async () => { Deno.test("override layouts", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/override`); const doc = await server.getHtml(`/override`);
assertSelector(doc, "body > .app > .override-layout > .override-page"); assertSelector(doc, "body > .app > .override-layout > .override-page");
}, },
); );
}); });
Deno.test("route overrides layout", async () => { Deno.test("route overrides layout", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/override/no_layout`); const doc = await server.getHtml(`/override/no_layout`);
assertSelector(doc, "body > .app > .no-layouts"); assertSelector(doc, "body > .app > .no-layouts");
}, },
); );
}); });
Deno.test("route overrides layout and app", async () => { Deno.test("route overrides layout and app", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_layouts/main.ts", "./tests/fixture_layouts/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/override/no_layout_no_app`); const doc = await server.getHtml(`/override/no_layout_no_app`);
assertSelector(doc, "body > .no-app-no-layouts"); assertSelector(doc, "body > .no-app-no-layouts");
}, },
); );
+10 -11
View File
@@ -14,11 +14,10 @@ import { BUILD_ID } from "../src/server/build_id.ts";
import { import {
assertSelector, assertSelector,
assertTextMany, assertTextMany,
fetchHtml,
parseHtml, parseHtml,
startFreshServer, startFreshServer,
waitForText, waitForText,
withFresh, withFakeServe,
withPageName, withPageName,
} from "./test_utils.ts"; } from "./test_utils.ts";
@@ -840,16 +839,16 @@ Deno.test(
); );
Deno.test("rendering custom _500.tsx page for default handlers", async (t) => { Deno.test("rendering custom _500.tsx page for default handlers", async (t) => {
await withFresh("./tests/fixture_custom_500/main.ts", async (address) => { await withFakeServe("./tests/fixture_custom_500/main.ts", async (server) => {
await t.step("SSR error is shown", async () => { await t.step("SSR error is shown", async () => {
const resp = await fetch(address); const resp = await server.get("/");
assertEquals(resp.status, Status.InternalServerError); assertEquals(resp.status, Status.InternalServerError);
const text = await resp.text(); const text = await resp.text();
assertStringIncludes(text, "Custom 500: Pickle Rick!"); assertStringIncludes(text, "Custom 500: Pickle Rick!");
}); });
await t.step("error page is shown with error message", async () => { await t.step("error page is shown with error message", async () => {
const doc = await fetchHtml(address); const doc = await server.getHtml("/");
const text = doc.querySelector(".custom-500")?.textContent!; const text = doc.querySelector(".custom-500")?.textContent!;
assertStringIncludes(text, "Custom 500: Pickle Rick!"); assertStringIncludes(text, "Custom 500: Pickle Rick!");
}); });
@@ -865,9 +864,9 @@ Deno.test("renders error boundary", async () => {
}); });
Deno.test("Resolves routes with non-latin characters", async () => { Deno.test("Resolves routes with non-latin characters", async () => {
await withFresh("./tests/fixture/main.ts", async (address) => { await withFakeServe("./tests/fixture/main.ts", async (server) => {
// Check that we can navigate to the page // Check that we can navigate to the page
const doc = await fetchHtml(`${address}/umlaut-äöüß`); const doc = await server.getHtml(`/umlaut-äöüß`);
assertSelector(doc, "h1"); assertSelector(doc, "h1");
assertTextMany(doc, "h1", ["it works"]); assertTextMany(doc, "h1", ["it works"]);
@@ -882,8 +881,8 @@ Deno.test("Resolves routes with non-latin characters", async () => {
}); });
Deno.test("Generate a single nonce value per page", async () => { Deno.test("Generate a single nonce value per page", async () => {
await withFresh("./tests/fixture/main.ts", async (address) => { await withFakeServe("./tests/fixture/main.ts", async (server) => {
const doc = await fetchHtml(address); const doc = await server.getHtml("/");
const nonceValues = Array.from( const nonceValues = Array.from(
new Set( new Set(
@@ -902,8 +901,8 @@ Deno.test("Generate a single nonce value per page", async () => {
}); });
Deno.test("Adds nonce to inline scripts", async () => { Deno.test("Adds nonce to inline scripts", async () => {
await withFresh("./tests/fixture/main.ts", async (address) => { await withFakeServe("./tests/fixture/main.ts", async (server) => {
const doc = await fetchHtml(`${address}/nonce_inline`); const doc = await server.getHtml(`/nonce_inline`);
const stateScript = doc.querySelector("#__FRSH_STATE")!; const stateScript = doc.querySelector("#__FRSH_STATE")!;
const nonce = stateScript.getAttribute("nonce")!; const nonce = stateScript.getAttribute("nonce")!;
+19 -20
View File
@@ -1,18 +1,17 @@
import { assertEquals } from "$std/testing/asserts.ts"; import { assertEquals } from "$std/testing/asserts.ts";
import { import {
assertTextMany, assertTextMany,
fetchHtml,
parseHtml, parseHtml,
waitForText, waitForText,
withFresh, withFakeServe,
withPageName, withPageName,
} from "./test_utils.ts"; } from "./test_utils.ts";
Deno.test("applies only _layout file of one group", async () => { Deno.test("applies only _layout file of one group", async () => {
await withFresh( await withFakeServe(
"./tests/fixture/main.ts", "./tests/fixture/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/route-groups`); const doc = await server.getHtml(`/route-groups`);
assertTextMany(doc, "p", ["Foo layout", "Foo page"]); assertTextMany(doc, "p", ["Foo layout", "Foo page"]);
}, },
@@ -20,20 +19,20 @@ Deno.test("applies only _layout file of one group", async () => {
}); });
Deno.test("applies only _layout files in parent groups", async () => { Deno.test("applies only _layout files in parent groups", async () => {
await withFresh( await withFakeServe(
"./tests/fixture/main.ts", "./tests/fixture/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/route-groups/baz`); const doc = await server.getHtml(`/route-groups/baz`);
assertTextMany(doc, "p", ["Bar layout", "Baz layout", "Baz page"]); assertTextMany(doc, "p", ["Bar layout", "Baz layout", "Baz page"]);
}, },
); );
}); });
Deno.test("applies only _layout files in parent groups #2", async () => { Deno.test("applies only _layout files in parent groups #2", async () => {
await withFresh( await withFakeServe(
"./tests/fixture/main.ts", "./tests/fixture/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/route-groups/boof`); const doc = await server.getHtml(`/route-groups/boof`);
assertTextMany(doc, "p", ["Bar layout", "Boof Page"]); assertTextMany(doc, "p", ["Bar layout", "Boof Page"]);
}, },
); );
@@ -52,10 +51,10 @@ Deno.test("can co-locate islands inside routes folder", async () => {
}); });
Deno.test("does not treat files in (_islands) as routes", async () => { Deno.test("does not treat files in (_islands) as routes", async () => {
await withFresh( await withFakeServe(
"./tests/fixture/main.ts", "./tests/fixture/main.ts",
async (address) => { async (server) => {
const res = await fetch(`${address}/route-groups-islands/invalid`); const res = await server.get(`/route-groups-islands/invalid`);
assertEquals(res.status, 404); assertEquals(res.status, 404);
await res.body?.cancel(); await res.body?.cancel();
}, },
@@ -63,10 +62,10 @@ Deno.test("does not treat files in (_islands) as routes", async () => {
}); });
Deno.test("does not treat files in (_...) as routes", async () => { Deno.test("does not treat files in (_...) as routes", async () => {
await withFresh( await withFakeServe(
"./tests/fixture/main.ts", "./tests/fixture/main.ts",
async (address) => { async (server) => {
const res = await fetch(`${address}/route-groups-islands/sub`); const res = await server.get(`/route-groups-islands/sub`);
assertEquals(res.status, 404); assertEquals(res.status, 404);
await res.body?.cancel(); await res.body?.cancel();
}, },
@@ -74,10 +73,10 @@ Deno.test("does not treat files in (_...) as routes", async () => {
}); });
Deno.test("resolve index route in group /(group)/index.tsx", async () => { Deno.test("resolve index route in group /(group)/index.tsx", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_group_index/main.ts", "./tests/fixture_group_index/main.ts",
async (address) => { async (server) => {
const res = await fetch(`${address}`); const res = await server.get(`/`);
assertEquals(res.status, 200); assertEquals(res.status, 200);
const doc = parseHtml(await res.text()); const doc = parseHtml(await res.text());
assertEquals(doc.querySelector("h1")?.textContent, "it works"); assertEquals(doc.querySelector("h1")?.textContent, "it works");
+16 -16
View File
@@ -2,7 +2,7 @@ import { assertEquals } from "./deps.ts";
import { import {
assertSelector, assertSelector,
assertTextMany, assertTextMany,
fetchHtml, withFakeServe,
withFresh, withFresh,
withPageName, withPageName,
} from "./test_utils.ts"; } from "./test_utils.ts";
@@ -12,10 +12,10 @@ Deno.test({
name: "render async server component", name: "render async server component",
async fn() { async fn() {
await withFresh( await withFakeServe(
"./tests/fixture_server_components/main.ts", "./tests/fixture_server_components/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}/basic`); const doc = await server.getHtml(`/basic`);
assertTextMany(doc, "h1", ["it works"]); assertTextMany(doc, "h1", ["it works"]);
}, },
); );
@@ -26,10 +26,10 @@ Deno.test({
name: "uses returned response", name: "uses returned response",
async fn() { async fn() {
await withFresh( await withFakeServe(
"./tests/fixture_server_components/main.ts", "./tests/fixture_server_components/main.ts",
async (address) => { async (server) => {
const res = await fetch(`${address}/response`); const res = await server.get(`/response`);
const text = await res.text(); const text = await res.text();
assertEquals(text, "it works"); assertEquals(text, "it works");
}, },
@@ -104,10 +104,10 @@ Deno.test({
name: "can call context.renderNotFound()", name: "can call context.renderNotFound()",
async fn() { async fn() {
await withFresh( await withFakeServe(
"./tests/fixture_server_components/main.ts", "./tests/fixture_server_components/main.ts",
async (address) => { async (server) => {
const res = await fetch(`${address}/fail`); const res = await server.get(`/fail`);
assertEquals(res.status, Status.NotFound); assertEquals(res.status, Status.NotFound);
const html = await res.text(); const html = await res.text();
@@ -144,10 +144,10 @@ Deno.test({
name: "renders async app template", name: "renders async app template",
async fn() { async fn() {
await withFresh( await withFakeServe(
"./tests/fixture_async_app/main.ts", "./tests/fixture_async_app/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}`); const doc = await server.getHtml(``);
assertSelector(doc, "html > body > .app > .layout > .page"); assertSelector(doc, "html > body > .app > .layout > .page");
}, },
); );
@@ -155,10 +155,10 @@ Deno.test({
}); });
Deno.test("define helpers", async () => { Deno.test("define helpers", async () => {
await withFresh( await withFakeServe(
"./tests/fixture_define_helpers/main.ts", "./tests/fixture_define_helpers/main.ts",
async (address) => { async (server) => {
const doc = await fetchHtml(`${address}`); const doc = await server.getHtml(``);
assertSelector(doc, "html > body > .app > .layout > .page"); assertSelector(doc, "html > body > .app > .layout > .page");
assertTextMany(doc, "p", ["Layout: it works", "Page: it works"]); assertTextMany(doc, "p", ["Layout: it works", "Page: it works"]);
}, },
+91 -3
View File
@@ -1,20 +1,38 @@
import { colors } from "$fresh/src/server/deps.ts"; import { colors, toFileUrl } from "$fresh/src/server/deps.ts";
import { assert } from "$std/_util/asserts.ts"; import { assert } from "$std/_util/asserts.ts";
import * as path from "$std/path/mod.ts"; import * as path from "$std/path/mod.ts";
import {
FromManifestOptions,
Manifest,
ServeHandlerInfo,
ServerContext,
} from "$fresh/server.ts";
import { import {
assertEquals, assertEquals,
basename,
delay, delay,
dirname,
DOMParser, DOMParser,
HTMLElement, HTMLElement,
HTMLMetaElement, HTMLMetaElement,
join,
Page, Page,
puppeteer, puppeteer,
TextLineStream, TextLineStream,
} from "./deps.ts"; } from "./deps.ts";
export function parseHtml(input: string): Document { export interface TestDocument extends Document {
debug(): void;
}
export function parseHtml(input: string): TestDocument {
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
return new DOMParser().parseFromString(input, "text/html") as any; const doc = new DOMParser().parseFromString(input, "text/html") as any;
Object.defineProperty(doc, "debug", {
value: () => console.log(prettyDom(doc)),
enumerable: false,
});
return doc;
} }
export async function startFreshServer(options: Deno.CommandOptions) { export async function startFreshServer(options: Deno.CommandOptions) {
@@ -207,6 +225,76 @@ export async function withPageName(
} }
} }
export interface FakeServer {
request(req: Request): Promise<Response>;
getHtml(pathname: string): Promise<TestDocument>;
get(pathname: string): Promise<Response>;
}
async function handleRequest(
handler: ReturnType<ServerContext["handler"]>,
conn: ServeHandlerInfo,
req: Request,
) {
let res = await handler(req, conn);
// Follow redirects
while (res.headers.has("location")) {
const loc = res.headers.get("location");
const hostname = conn.remoteAddr.hostname;
res = await handler(new Request(`https://${hostname}${loc}`), conn);
}
return res;
}
export async function fakeServe(
manifest: Manifest,
options: FromManifestOptions,
): Promise<FakeServer> {
const ctx = await ServerContext.fromManifest(manifest, options);
const handler = ctx.handler();
const conn: ServeHandlerInfo = {
remoteAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
};
const origin = `https://127.0.0.1`;
return {
request(req) {
return handler(req, conn);
},
async getHtml(pathname) {
const req = new Request(`${origin}${pathname}`);
const res = await handleRequest(handler, conn, req);
return parseHtml(await res.text());
},
get(pathname: string) {
const req = new Request(`${origin}${pathname}`);
return handleRequest(handler, conn, req);
},
};
}
export async function withFakeServe(
name: string,
cb: (server: FakeServer) => Promise<void> | void,
) {
const fixture = join(Deno.cwd(), name);
const dev = basename(name) === "dev.ts";
const manifestPath = toFileUrl(join(dirname(fixture), "fresh.gen.ts")).href;
const manifestMod = await import(manifestPath);
const server = await fakeServe(manifestMod.default, { dev });
await cb(server);
}
export async function startFreshServerExpectErrors( export async function startFreshServerExpectErrors(
options: Deno.CommandOptions, options: Deno.CommandOptions,
) { ) {
+20 -18
View File
@@ -1,7 +1,12 @@
import { assert, assertEquals, assertMatch, delay, puppeteer } from "./deps.ts"; import { assert, assertEquals, assertMatch, delay, puppeteer } from "./deps.ts";
import { cmpStringArray } from "./fixture_twind_hydrate/utils/utils.ts"; import { cmpStringArray } from "./fixture_twind_hydrate/utils/utils.ts";
import { startFreshServer, withFresh, withPageName } from "./test_utils.ts"; import {
startFreshServer,
withFakeServe,
withFresh,
withPageName,
} from "./test_utils.ts";
/** /**
* Start the server with the main file. * Start the server with the main file.
@@ -339,24 +344,21 @@ Deno.test({
}); });
// Test for: https://github.com/denoland/fresh/issues/1655 // Test for: https://github.com/denoland/fresh/issues/1655
Deno.test({ Deno.test("don't duplicate css class", async () => {
name: "don't duplicate css class", await withFakeServe(
async fn() { "./tests/fixture_twind_app/main.ts",
await withFresh( async (server) => {
"./tests/fixture_twind_app/main.ts", const res = await server.get(`/app_class`);
async (address) => { assertEquals(res.status, 200);
const res = await fetch(`${address}/app_class`);
assertEquals(res.status, 200);
// Don't use an HTML parser here which would de-duplicate the // Don't use an HTML parser here which would de-duplicate the
// class names automatically // class names automatically
const html = await res.text(); const html = await res.text();
assertMatch(html, /html class="bg-slate-800">/); assertMatch(html, /html class="bg-slate-800">/);
assertMatch(html, /head class="bg-slate-800">/); assertMatch(html, /head class="bg-slate-800">/);
assertMatch(html, /body class="bg-slate-800">/); assertMatch(html, /body class="bg-slate-800">/);
}, },
); );
},
}); });
// Test for: https://github.com/denoland/fresh/issues/1655 // Test for: https://github.com/denoland/fresh/issues/1655