Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

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

    Testing components and HTTP consumers

    Use managed Chromium component tests for Preact components, islands, stores, and browser hooks. Use contract-aware MSW handlers when the subject calls HTTP; do not substitute them for route-harness tests.

    Name the test *.client.test.tsx and run one file first. You do not need a prior build or browser install in the normal path; Brix prepares Chromium and application Panda CSS when the selected suite runs. The completed test should assert user-visible behavior through accessible queries.

    Managed lint enforces direct runtime import/export boundaries with brix/test-environment: ordinary *.test/spec.{js,jsx,ts,tsx} files cannot use brix/test/browser, while *.client.test/spec files cannot import or re-export the named server-only helpers createTestHarness, mockFragment, or testDataCacheStore from brix/test, even under aliases. Type-only specifiers, shared src/test/ helpers, stories, and *.test-d.ts are exempt. This is not whole-program analysis: namespace member use, star re-exports from brix/test, dynamic imports, and indirect helper modules are not traced. If a custom test environment uses different file selection, append a matching Oxlint config overrides entry with "brix/test-environment": "off" rather than changing shared helpers to satisfy a global policy.

    Render a browser component

    #

    Name the file *.client.test.tsx and import browser helpers through Brix:

    import { describe, expect, it } from "brix/test";
    import { render, userEvent } from "brix/test/browser";
    import { BookingButton } from "./BookingButton.tsx";
    
    describe("BookingButton", () => {
      it("submits a booking", async () => {
        const screen = await render(<BookingButton />);
        await userEvent.click(screen.getByRole("button", { name: "Book" }));
        await expect.element(screen.getByText("Booked")).toBeVisible();
      });
    });
    

    brix/test/browser exports render, renderWithTranslations, page, and userEvent. Both renderers are asynchronous: await render and renderWithTranslations, and await the returned rerender and unmount. Locators match text exactly and case-sensitively by default; use toMatchTextContent for partial text or regular expressions. Await interactions and browser assertions.

    Mount the production translation provider when the component uses translation hooks:

    await renderWithTranslations(<CheckoutButton />, {
      locale: "sv",
      messages: { "checkout.submit": "Fortsätt" },
      isProduction: false,
    });
    

    The renderer is Preact-only. Managed React applications test their components in the React application's browser toolchain.

    Test component styling

    #

    Managed component tests automatically generate and load the application's Panda CSS, including panda.config.ts, tokens, recipes, preflight, and global styles. This works on a clean checkout without a prior build or a manual stylesheet import. Panda is built in; customize panda.config.ts instead of passing the removed panda option to defineBrixConfig.

    The test mounts the component, not the full application shell. Supply required providers, layout wrappers, and theme selectors explicitly, and import any separate stylesheets that the shell normally loads. For example, add the dark class to the document element when testing dark-mode tokens and remove it during cleanup.

    Interaction and visibility assertions do not prove padding, typography, or responsive layout. Add computed-style assertions or screenshot comparisons for important visual behavior, and exercise the relevant viewport sizes and component variants.

    Test stores and hooks through a consumer

    #

    Render a small component that calls the hook and exposes meaningful state through accessible UI. Wrap it in the real generated provider when testing a store:

    function CartSummary() {
      const cart = useCartStore();
      // The hook returns null outside its provider.
      if (!cart) return null;
      return <button onClick={() => cart.add("sku-123")}>Items {cart.items.value.length}</button>;
    }
    
    await render(
      <CartStoreProvider initialItems={[]}>
        <CartSummary />
      </CartStoreProvider>,
    );
    
    await userEvent.click(page.getByRole("button", { name: "Items 0" }));
    await expect.element(page.getByRole("button", { name: "Items 1" })).toBeVisible();
    

    This verifies provider setup, signals, rerendering, and user-visible behavior together. For a hook without visible output, use a tiny local test component to expose its result, but prefer behavior over internal implementation state. Use vi.fn or vi.spyOn for callback boundaries; do not replace modules.

    Mock HTTP consumers with MSW

    #

    mockContract and mockContractError produce typed MSW handlers for executeApi, useApi, browser components, and other HTTP-consuming code. Initialize the version-matched browser worker once:

    brix msw init public --save
    

    Brix manages MSW 3. Configure the unhandled-request policy with onUnhandledFrame, and return or await worker.stop() during teardown because shutdown is asynchronous. Regenerate the service worker with the command above whenever a Brix upgrade changes the managed MSW version. In raw http.* handlers and mockContract resolvers, read cookies through the cookies argument, not the request's cookie header; Node interception keeps no cookie jar. Delayed responses respect fake timers, so advance them explicitly. brix/msw follows MSW's root exports, which do not include GraphQL or handleRequest; brix/msw/browser and brix/msw/node provide the worker and server setups.

    import { afterAll, afterEach, beforeAll, expect, it } from "brix/test";
    import { mockContract, mockContractError } from "brix/test";
    import { setupWorker } from "brix/msw/browser";
    import { page, render, userEvent } from "brix/test/browser";
    import { getItemsApiContract } from "./contract.ts";
    import { ItemList } from "./ItemList.tsx";
    
    const worker = setupWorker();
    
    beforeAll(() => worker.start({ onUnhandledFrame: "error" }));
    afterEach(() => worker.resetHandlers());
    afterAll(() => worker.stop());
    
    it("loads items", async () => {
      worker.use(
        mockContract(getItemsApiContract, {
          data: [{ id: "item-1", name: "Backpack" }],
        }),
      );
    
      await render(<ItemList />);
      await userEvent.click(page.getByRole("button", { name: "Load items" }));
      await expect.element(page.getByText("Backpack")).toBeVisible();
    });
    
    it("shows an API error", async () => {
      worker.use(mockContractError(getItemsApiContract, 503));
      await render(<ItemList />);
      await userEvent.click(page.getByRole("button", { name: "Load items" }));
      await expect.element(page.getByRole("alert")).toBeVisible();
    });
    

    For an HTTP consumer running in the Node project, use the same contract mocks with setupServer from brix/msw/node, then listen in beforeAll, resetHandlers in afterEach, and close in afterAll.

    Mock success data is required when the contract declares a response and omitted for an empty response such as { status: 204 }. Fixtures use response-schema input, are JSON-normalized and validated, and produce parsed output in the client. A request-aware sync or async resolver receives typed params, parsed body and query, MSW-resolved cookies, plus the original request:

    Resolvers decode JSON or URL-encoded forms according to the contract, then apply the body schema once. Form content-type mismatches and duplicate fields fail parsing. As on createApiRoute, a JSON body fails when its Content-Type is not application/json or application/*+json, or when a nonempty body has none; a raw fetch with a string body and no headers sends text/plain and is rejected. Static response fixtures do not parse request bodies; use a resolver when verifying what a component sends.

    mockContract(updateItemApiContract, {
      status: 201,
      data: ({ params, body, request }) => ({
        id: params.itemId,
        name: body.name,
        requestId: request.headers.get("x-request-id"),
      }),
    });
    

    Use baseUrl to pin a handler to an external origin; the default matches any origin. Like executeApi, one trailing slash is removed, and a relative baseUrl such as /api matches that path prefix on any origin. A { status: 204 } mock still validates the request and runs a resolver, which must return undefined; 204 data or a response schema that rejects undefined fails the test. mockContractError(contract, status, { data?, baseUrl? }) preserves explicit falsy JSON error bodies and otherwise returns { error: "Mock <status> error" }.

    Do not use these handlers to test the corresponding Brix route. Use the route harness, which exercises middleware, environment, auth, rendering, and server error handling.

    Debug browser tests

    #

    Run one component file or the browser project:

    brix test src/features/checkout/BookingButton.client.test.tsx
    brix test --project browser
    brix test src/features/checkout/BookingButton.client.test.tsx --browser.traceView --reporter=html
    

    Generated traces, reports, screenshots, and attachments go under .vitest/. Commit reference screenshots under __screenshots__/, not generated .vitest/ output. Use brix test --repeats 20 <test-file> to reproduce order-independent flakes.

    Use route tests for the server endpoint behind a component and E2E tests only when navigation or SSR-to-hydration integration is the subject.