diff --git a/docs/latest/testing/index.md b/docs/latest/testing/index.md index d4e8588c..47e5abe3 100644 --- a/docs/latest/testing/index.md +++ b/docs/latest/testing/index.md @@ -104,35 +104,129 @@ Deno.test("MyLayout - renders heading and content", async () => { }); ``` -## Testing with file routes and islands +## Testing routes and handlers -[File routes](/docs/concepts/file-routing) are collected by the -[`Builder`](/docs/advanced/builder) class and not just by -[`App`](/docs/concepts/app) alone. We can generate a snapshot and re-use it for -many app instances in our test suite. +For testing your route handlers and business logic, you can use the same +[`App`](/docs/concepts/app) pattern shown above. Fresh 2.0 makes it easy to test +individual routes without needing a full build process: -```ts my-app.test.ts -import { createBuilder } from "vite"; -// Best to do this once instead of for every test case for -// performance reasons. -const builder = await createBuilder({ - root: "./path/to/app", - build: { - emptyOutDir: true, - }, -}); -await builder.build(); +```ts my-routes.test.ts +import { expect } from "@std/expect"; +import { App } from "fresh"; -const { app } = await import("./path/to/app/_fresh/server.js"); +// Import your route handlers +import { handler as indexHandler } from "./routes/index.ts"; +import { handler as apiHandler } from "./routes/api/users.ts"; -Deno.test("My Test", async () => { +Deno.test("Index route returns homepage", async () => { + const app = new App().get("/", indexHandler); const handler = app.handler(); - const response = await handler(new Request("http://localhost")); + const response = await handler(new Request("http://localhost/")); const text = await response.text(); - if (text !== "hello") { - throw new Error("fail"); + expect(text).toContain("Welcome"); +}); + +Deno.test("API route returns JSON", async () => { + const app = new App().get("/api/users", apiHandler); + const handler = app.handler(); + + const response = await handler(new Request("http://localhost/api/users")); + const json = await response.json(); + + expect(json).toEqual({ users: [] }); +}); +``` + +## Testing islands + +Testing islands requires different approaches for server-side and client-side +behavior: + +### Server-side rendering of islands + +You can test that your islands render correctly on the server using the same +[`App`](/docs/concepts/app) pattern. Note: this requires a `.tsx` file extension +to use JSX: + +```tsx island-ssr.test.tsx +import { expect } from "@std/expect"; +import { App } from "fresh"; +import Counter from "./islands/Counter.tsx"; + +Deno.test("Counter page renders island", async () => { + const app = new App().get("/counter", (ctx) => { + return ctx.render( +