Testing
New Routa projects ship with Vitest, a test script, and a starter test beside the
generated /status route. This guide covers the three levels worth testing, how to replace
services in an in-memory test application, and where Routa’s own checks already cover you.
Before You Start
Section titled “Before You Start”- A project created by
create-routa-ts, or Vitest installed and atestscript added. - A passing
routa check. Contract errors are cheaper to find there than in a test run.
-
Run the existing tests.
Terminal window npm run testTerminal window pnpm run testTerminal window yarn run testTerminal window bun run test -
Test a schema directly when you want to pin the shape of a payload. This is what the generated starter test does.
src/routes/status/route.test.ts import { describe, expect, it } from "vitest";import { GetStatusResponse } from "./schemas.js";describe("GET /status", () => {it("accepts the documented success response", () => {expect(GetStatusResponse.safeParse({ ok: true }).success).toBe(true);});}); -
Test a handler by calling its
rundirectly. It is a plain function, so passinput,ctx, andresponse, then assert on the outcome name. The response builders are pure functions that return result objects, so a test can supply its own. This test targets aGETthat declaressuccessandnotFoundoutcomes.src/routes/users/$userId/route.test.ts import { createLogger } from "@routa-ts/core/logger";import { describe, expect, it } from "vitest";import route from "./route.js";type GetUserArgs = Parameters<typeof route.get.run>[0];const ctx = { logger: createLogger({ enabled: false }) };const response: GetUserArgs["response"] = {success: (data) => ({ type: "success", data }),notFound: () => ({ type: "notFound" }),};describe("GET /users/:userId", () => {it("returns notFound for an unknown user", async () => {const result = await route.get.run({ input: { params: { userId: "nope" } }, ctx, response });expect(result.type).toBe("notFound");});}); -
Test the full application when routing, middleware, parsing, services, and serialization all matter. Import
createTestAppfrom the generated.routa/testing.gen.js. It builds an isolated, in-memory instance of your project, with no network listener and no app argument, andrequestsends a request through it.src/users.test.ts import { afterEach, describe, expect, it } from "vitest";import { createTestApp } from "../.routa/testing.gen.js";describe("POST /users", () => {let app: Awaited<ReturnType<typeof createTestApp>> | undefined;afterEach(async () => {await app?.dispose();});it("rejects a body that fails validation", async () => {app = await createTestApp();const response = await app.request("/users", {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ name: "" }),});expect(response.status).toBe(400);});});Without options,
createTestAppruns your production service factories. A path passed torequestresolves againsthttp://localhost; aURLorRequestworks too. -
Replace services with test doubles. Write the doubles in an ordinary file, and annotate each factory with the generated
ServicesFactorytype for its scope. TypeScript then checks the factory against the scope’s contract and the context it receives, so you do not repeat either interface. This example uses theAppServices,OrdersServices, andCheckoutServicescontracts from Services.src/testing/fakes.ts import type { OrderBook, Receipts } from "../orders/services.js";import type { ServicesFactory } from "../../.routa/testing.gen.js";export class MemoryOrderBook implements OrderBook {readonly placed: Array<{ id: string; total: number }> = [];constructor(readonly owner: string) {}async list() {return this.placed;}async place(total: number) {const order = { id: `order-${this.placed.length + 1}`, total };this.placed.push(order);return order;}}export const sentReceipts: string[] = [];const receipts: Receipts = {send: (orderId) => sentReceipts.push(orderId),};export const testAppServices: ServicesFactory<"application"> = () => ({clock: { now: () => new Date("2030-01-01T00:00:00.000Z") },users: { find: async (id) => ({ id, name: "Ada" }) },});export const testOrdersServices: ServicesFactory<"/orders"> = ({ ctx }) => ({orders: new MemoryOrderBook(ctx.auth.userId),});export const testCheckoutServices: ServicesFactory<"POST /orders"> = ({ onCleanup }) => {onCleanup(() => sentReceipts.splice(0));return { receipts };};Pass a lone application factory, or replace route-file and method scopes by path:
src/orders.test.ts import { expect, it } from "vitest";import { createTestApp } from "../.routa/testing.gen.js";import { testAppServices, testCheckoutServices } from "./testing/fakes.js";it("serves the users route with test application services", async () => {const app = await createTestApp(testAppServices);try {expect((await app.request("/users/u1")).status).toBe(200);} finally {await app.dispose();}});it("places an order with a test receipt outbox", async () => {const app = await createTestApp({services: testAppServices,routes: {"/orders": { methods: { post: { services: testCheckoutServices } } },},});try {const response = await app.request("/orders", {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ total: 12 }),});expect(response.status).toBe(201);} finally {await app.dispose();}});In the second test the route file’s production factory still runs, and it receives the test
clockthroughctx.services. Only the scopes you name are replaced. To replace the route file’s factory too, addservices: testOrdersServicesbesidemethods.
Verify
Section titled “Verify” ✓ src/routes/status/route.test.ts (1 test) 3ms
Test Files 1 passed (1) Tests 1 passed (1)What to Test Where
Section titled “What to Test Where”| Level | Use it for | Do not use it for |
|---|---|---|
| Schema | Payload shapes, coercion, optionality | Anything requiring a request |
| Handler | Outcome selection and service orchestration | Validation and status mapping, which Routa owns |
| HTTP | Middleware chains, parsing, status codes, content negotiation | Business rules better tested in services |
Business logic belongs in application-owned services and should be tested there, without Routa in the picture at all. A route test that needs a database is usually testing the wrong layer.
What You Do Not Need to Test
Section titled “What You Do Not Need to Test”Routa’s own checks already cover these, so tests asserting them only duplicate the framework:
- That an undeclared response type is rejected —
routa checkreportsROUTA_RESULT_TYPE. - That every method declares a 2xx response —
ROUTA_MISSING_SUCCESS_RESPONSE. - That middleware ordering satisfies
requires—ROUTA_MIDDLEWARE_ORDER. - That the OpenAPI document matches the source —
routa openapi check.
Run those as part of the same pipeline:
npm run checknpm run testnpm run openapi:checkpnpm run checkpnpm run testpnpm run openapi:checkyarn run checkyarn run testyarn run openapi:checkbun run checkbun run testbun run openapi:checkReplacing Services
Section titled “Replacing Services”Each entry in createTestApp options replaces one scope’s whole factory before the
application is built:
servicesreplaces the application factory. Passing a factory directly is the same.routes["/orders"].servicesreplaces the route file’s factory.routes["/orders"].methods.post.servicesreplaces the method’s factory.
A replacement returns the scope’s complete contract, as the original does. Routa checks its
names at runtime exactly as in production. The original factory of a replaced scope never
runs, so it acquires nothing. Omitted scopes keep their production factories and receive the
services of earlier scopes, including replacements, through ctx.
TypeScript rejects a path no route file declares, a method the route file does not declare,
a route or method that declares no services, and a factory that returns an incomplete or
wrong contract. When a call slips past the types, for example through a cast,
createTestApp rejects an unknown path, method, or scope, or a value that is not a factory,
before any factory runs:
TypeError: Cannot replace services for GET /orders: it declares none.A replacement’s returned names are checked only when it runs: at construction for the
application scope, and on a matching request for a route or method scope, which then
responds with 500. Routa never checks service members at runtime.
Importing .routa/testing.gen.js imports none of your modules and runs no factory. Your
modules load when you call createTestApp, so their own import-time effects still run then.
Plain imports are not replaced; inject a dependency as a service when a test needs to swap
it.
Cleanup and Disposal
Section titled “Cleanup and Disposal”Each test application has its own factory calls and cleanup. Two applications built in the same test share nothing Routa owns. Each factory that runs, original or replacement, registers cleanup for the resources it acquired, and Routa releases them on the same schedule as in production:
- When an application factory fails, Routa releases the cleanup it already registered,
and
createTestApprejects with the factory’s error. - When a route-file or method factory fails, Routa releases that request’s cleanup, and
the matching
requestresolves with a500response. requestsettles after the request’s method and route-file services are released.dispose()stops accepting requests, waits for accepted requests and their cleanup, then releases application services in reverse registration order. Arequestafter disposal starts rejects.- Repeated and concurrent
dispose()calls share one outcome. When a cleanup callback fails,dispose()rejects with anAggregateErrorafter attempting every callback.
dispose() sets no deadline and cancels nothing. A request or cleanup callback that never
settles keeps it pending, and your test runner’s timeout reports the hang. Always await
dispose(), in a finally block or an afterEach hook.
Troubleshooting
Section titled “Troubleshooting”| Problem | Fix |
|---|---|
Imports fail with ERR_MODULE_NOT_FOUND |
Use .js extensions in relative imports. Generated projects are ESM. |
A handler test cannot construct ctx |
Pass the keys the route’s middleware provides, plus a logger. createLogger({ enabled: false }) keeps test output clean. |
A handler reads ctx.services |
Pass services in ctx with test implementations of the contract, or replace the scope’s factory in createTestApp. |
Type errors on route.get.run |
Metadata is stale. Run routa generate. |
.routa/testing.gen.ts does not list ... |
You added a route or middleware file since the last generation. Run routa generate. |
Vitest picks up files under .routa/ |
Generated metadata contains no tests; narrow include in the Vitest config if a glob is too broad. |