Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / Testing and tooling / TestingRead Markdown
    On this page

    Testing routes and server behavior

    Use Brix's shared route harness to test API, page, and fragment routes through production registration, middleware, rendering, environment parsing, and error handling without starting a server.

    Prerequisites: a discovered route and the application's generated src/test/harness.ts. Start with one success case and one meaningful failure case. The expected outcome is a real production-configured request without a listening port, provider credentials, or module replacement.

    Harness options require query when its schema input has required keys. Contract mocks match the same Brix path grammar as mounted routes, including omitted optional parameters, parameter names with - or ., static colons such as /v1/items:search, constrained parameters, and terminal wildcards; wildcard resolver params use the "*" key and contain a string tail.

    Create the application harness

    #

    Generated and adopted applications include src/test/harness.ts. Keep createApp for normal application tests so every request receives a fresh production-configured app:

    import { createTestHarness } from "brix/test";
    import { createBrixApp } from "brix/server";
    import { brixServer } from "#brix/server";
    import type { CoercedEnvSchema } from "#/env.generated.d.ts";
    
    type Setup = { user?: true | { id: string; role: string }; tenant?: string };
    
    export const { testApi, testFragment, testPage, testResponse, withOptions } =
      createTestHarness<Setup>({
        createApp: () => createBrixApp(brixServer),
        env: { STAGE: "test-run", VERSION: "test" } satisfies CoercedEnvSchema,
        setupContext: async ({ user, tenant }) => ({
          state: {
            ...(user ? { user: user === true ? { id: "user-1", role: "member" } : user } : {}),
            ...(tenant ? { tenant } : {}),
          },
        }),
      });
    
    export const authenticated = withOptions({ user: true });
    

    setupContext may asynchronously create request-scoped users, tenants, or services. Brix awaits it once per harness call (testApi, testPage, testFragment, or testResponse) and assigns the returned properties to every request in that call, including composed fragment requests. With createBrixApp, the properties are assigned after Brix's request-ID, environment, logging, security, and asset middleware, and before locale finalization, translation middleware, defineBrixServer middleware, harness middleware, and routes. A custom createApp receives them after middleware it registered itself, so register context-dependent test middleware in the harness middleware option. setupContext supplements production middleware rather than replacing it. Omit createApp only for an intentionally isolated library route.

    createApp must build a new app for each request. Brix ignores later route mounts on an app, so returning an app that a previous harness request used throws instead of serving its first route. An app that already has Brix routes mounted is accepted only when those routes include the tested route (and any fragments passed to testPage); otherwise the harness throws instead of returning a 404. Such an app also throws when the harness configures middleware: Hono would run the mounted route handlers before middleware registered afterwards. A pre-mounted custom app rejects setupContext, locale, and translations for the same reason.

    Setup options are the keys outside the built-in request options. body, params, query, pageQuery, representation, fragments, headers, cookies, locale, and translations are never forwarded to setupContext, even when bound with withOptions; do not use them as setup keys. JSON request bodies default to Content-Type: application/json, and an explicit JSON Content-Type header is preserved as executeApi preserves it.

    Keep production logging, error handling, and authentication installed. Replacing them with no-op test helpers can make a request pass without exercising the application's actual policy.

    The env snapshot is installed before production middleware and parsed by the production snapshot parser. It never falls back to process globals. Malformed snapshots and forbidden process-control keys fail closed, but the parser does not rerun Varlock's application schema or check required application keys against CoercedEnvSchema. Supply a complete fixture matching your schema; the STAGE and VERSION above are illustrative, not universal built-in values. The generated harness types the fixture with satisfies CoercedEnvSchema, so brix check reports a key added to env/.env.schema but missing from the fixture; values in env/.env.test-run do not reach harness requests. This is the normal way to test request environment behavior; reserve brix test --env and --stage for deliberate environment-loading integration tests.

    Each request gets a fresh app, but server-scoped services built by defineBrixServer persist for the module-level brixServer. A static dataCache configuration creates one cache and memory store, so data cached by one test is returned to later tests in the same file that stub the same upstream differently. Reset it between tests, or configure dataCache as a per-request factory:

    import { afterEach } from "brix/test";
    import { brixServer } from "#brix/server";
    
    afterEach(() => brixServer.dataCache.invalidateAll());
    

    The example's state.user also assumes your production auth integration reads that project-owned context shape; it does not populate Hono's c.get("user") or make the session-based auth example in server authentication succeed. Brix does not authenticate a request merely because a test passes user: true. Adapt setupContext to your real auth seam, or send the cookie/header that your production middleware validates. Include both anonymous and authenticated cases so a fixture cannot silently bypass the policy you intended to test.

    Test an API route

    #
    import { expect, it } from "brix/test";
    import { authenticated, testApi } from "#brix/test";
    import { updateProfileApiRoute } from "./route.ts";
    
    it("rejects anonymous requests", async () => {
      const response = await testApi(updateProfileApiRoute, {
        params: { profileId: "profile-123" },
        body: { displayName: "Ada" },
      });
      expect(response.status).toBe(401);
      expect(response.error).toEqual({ error: "Unauthorized" });
    });
    
    it("updates an authenticated profile", async () => {
      const response = await authenticated.testApi(updateProfileApiRoute, {
        params: { profileId: "profile-123" },
        body: { displayName: "Ada" },
      });
      expect(response.status).toBe(200);
      expect(response.expectSuccess().displayName).toBe("Ada");
    });
    

    The route retains its contract. Required bodies and exact path params are enforced by TypeScript; body and query inputs are parsed as production handlers expect. Options also include headers, cookies, locale, and request-local translations. Additional setup keys are passed to setupContext. A locale must be one of the application's configured locales; any other value throws Unsupported Brix test locale before the request is sent.

    Required query input cannot be bypassed by omitting options, including object unions with disjoint required keys. This applies to testApi, testPage, and bound withOptions harnesses. Paths whose parameters are all optional allow omitted params, just like clients and direct route execution.

    For optional/defaulted JSON body schemas, pass body: undefined to send no body. The route and request-aware mockContract resolvers both parse this as undefined, applying schema defaults. Whitespace-only, BOM-only, and malformed nonempty JSON remain invalid; JSON null is not absence.

    testApi uses the contract's request encoding. For bodyEncoding: "form-urlencoded", pass a plain string-valued object; the harness serializes it and sets the form content type before exercising the real parser. It rejects unsupported outgoing values or conflicting headers. Use an application-level request with raw bytes when testing duplicate fields or missing/wrong content types; those malformed exchanges cannot be produced by the typed serializer.

    testApi returns status, typed successful data, parsed error, unmodified text, headers, and a clone-safe raw response. expectSuccess() throws with the status for non-2xx responses and otherwise returns the non-optional typed payload. Assert the status and error payload directly when testing application error mapping or thrown HTTPExceptions.

    Successful nonempty bodies must be valid JSON, including middleware short-circuits: malformed JSON rejects testApi before schema parsing, just as the HTTP client rejects it. Empty bodies are parsed as undefined so response defaults and transforms still apply. Error responses retain the JSON-or-text fallback for inspection. Use testResponse for successful non-JSON endpoints.

    For a native response route, use testResponse(route, options). It returns the native, unconsumed Response, does not follow redirects, and does not JSON-encode or pre-read the body. Options include typed params and query input plus native body: BodyInit, headers, cookies, locale, translations, and project setup fields. Configure setupContext and env on the harness. Required path/query input makes options required. Clone before reading when multiple assertions need the body.

    Test a rendered page

    #
    const response = await testPage(productDetailsPageRoute, {
      locale: "sv",
      params: { productId: "sku-123" },
      query: { preview: true },
      user: true,
    });
    
    expect(response.status).toBe(200);
    expect(response.html).toContain("sku-123");
    expect(response.headers.get("content-language")).toBe("sv");
    

    The harness constructs the URL from the page contract, preserving locale, params, query serialization, route validation, global middleware, security headers, renderer, and server error handling. A shared page path also accepts locale to set the request locale.

    Harness responses use development render semantics because no build has run: the default Content Security Policy keeps ws: and wss: in connect-src, pages contain development hydration scripts, and there is no build manifest for modulepreloads or the production island bootstrap. Verify production HTML, CSP, and hydration markup against a built application or a production server in an end-to-end suite.

    To test an opted-in semantic representation, pass representation: "markdown" and assert response.markdown; the response type prevents reading HTML from a Markdown result.

    Test fragments and composition

    #

    Test fragment endpoint loading and transport directly:

    const endpoint = await testFragment(BookingWidgetFragment, {
      params: { hotelId: "hotel-1" },
      pageQuery: { campaign: "summer" },
    });
    
    expect(endpoint.status).toBe(200);
    expect(endpoint.html).toContain("hotel-1");
    

    Test a page with real in-process fragment routes, or replace selected edge responses with typed deterministic mocks:

    import { mockFragment } from "brix/test";
    
    const response = await testPage(bookingPageRoute, {
      query: { campaign: "summer" },
      fragments: [
        mockFragment(
          BookingWidgetFragment,
          ({ params, pageQuery }) => `<aside data-mock>${params.hotelId}:${pageQuery.campaign}</aside>`,
        ),
      ],
    });
    

    Pass fragment route objects instead of mocks to exercise their real loaders. testPage sends the production defer header, renders placeholders, forwards declared page query, and runs the production composer. A mock receives only public endpoint params and forwarded query—not server-loaded props. Missing registrations, invalid transport, endpoint failures, and composition errors fail the test. Keep mockFragment in Node tests; it is not a browser component mock.

    Reuse authenticated and service scenarios

    #

    withOptions binds setup values, headers, cookies, translations, or fragments without mutable globals:

    const tenantAdmin = withOptions({
      user: { id: "admin-1", role: "admin" },
      tenant: "acme",
      headers: { "x-test-suite": "tenant-admin" },
    });
    
    const response = await tenantAdmin.testApi(updateProfileApiRoute, {
      params: { profileId: "profile-123" },
      body: { displayName: "Ada" },
    });
    

    Per-request values override bound defaults. Headers merge case-insensitively and cookies by case-sensitive name. Contract-required bodies and params remain required. Bound harnesses expose withOptions again, so suites can derive progressively specialized auth, tenant, and request-service scenarios.

    Use these tests for Brix application infrastructure. If the subject merely consumes an HTTP API, use contract-aware MSW mocks instead.

    An isolated route test does not prove production discovery or registration. Keep route modules at their supported flat feature locations; doctor and build diagnose unsupported nested locations. The assembled Node and generated HTTP Lambda production builds initialize the actual application without dispatching a request or resolving Brix environment providers, catching registration conflicts that isolated route tests cannot see. This initialization gate does not run for Cloudflare; verify that bundle in a Worker runtime separately.