Skip to main content
TESTING & ARCHITECTURE//6 MIN READ

What Writing a 3-Layer Vitest & React Testing Library Suite Actually Caught in Production Code

How I built a fast 3-layer test architecture with Vitest, React Testing Library, and TanStack Query—and the React 19 vs. 18 boundary bugs, hidden QueryClient crashes, and 401 token refresh edge cases it exposed immediately.

tests don't just prove code works—they expose hidden coupling.

Most test suites either mock so much that they test nothing, or require a full database and staging server just to verify a single UI state. When I set up the automated testing architecture for our service marketplace, I wanted a suite that ran in seconds locally with `npm test` while still catching real bugs across domain logic, React components, and server/API boundaries.

Vitest terminal output showing 3 test files and 10 tests passing across domain rules, API route handlers, and UI component states

1. What Running the Tests Immediately Exposed

Before the suite even finished its first green run, wiring up the tests surfaced three architectural issues in the codebase that manual clicking had missed:

  • React 19 vs. React 18 Boundary Between `/` and `/admin`: When a test in the root project tried to render a component imported from `admin/src/`, React threw 'A React Element from an older version of React was rendered.' The main client app (`package.json`) runs on React 19, while `admin/package.json` resolved React 18 from its own `admin/node_modules`. That immediately proved why sharing raw `.tsx` files across `src/` and `admin/src/` caused runtime friction and why keeping both apps strictly self-contained is essential.
  • Hidden QueryClient Dependency Inside ChatInbox Rows: `ChatInbox` rendered cleanly without a `QueryClientProvider` during its loading, error, and empty states. The exact moment we passed a populated chat item into the test, it crashed with `No QueryClient set`. Why? Each `ChatInboxCard` calls `useChatParticipant`, which internally fires a `@tanstack/react-query` `useQuery` hook to resolve fallback profile and quotation details. Without testing the populated data state in isolation, that hidden provider coupling would have stayed invisible.
  • Vite 8 Native `tsconfigPaths` Support: Vitest flagged that on Vite 8, the external `vite-tsconfig-paths` plugin is deprecated in favor of Vite's built-in `resolve: { tsconfigPaths: true }`. Switching to the native resolver in `vitest.config.ts` eliminated the deprecation warning and shaved startup overhead.
"Testing loading, error, and empty states is easy. The real bugs hide in the populated state where child hooks quietly reach for context providers."

2. How the 3-Layer Test Architecture Works

When `npm test` runs, Vitest spins up a simulated browser DOM (`jsdom`) via `vitest.config.ts` and resets DOM state cleanly after every assertion using `src/test/setup.ts`. I structured the 10 core test suites into three distinct layers so the entire run completes in a few seconds without requiring a live backend server.

Layer 1: Business & Domain Rules (`src/test/utils-and-domain.test.ts`)

The first layer tests pure functions that guard the most high-risk financial and marketplace rules:

  • Review Eligibility Guard (`reviewEligibility`): Passes mock job payloads through `reviewEligibility` across four edge cases—allowing a valid customer on a completed job with a numeric `artisan_profile_id: 19`, blocking a random user UUID not attached to the job, blocking jobs still `in_progress`, and blocking any job where `artisan_profile_id` is `null` so the UI never accidentally sends a raw User UUID to `/profiles/artisans/{id}/rate/`.
  • Escrow & Job Progress State Machine (`jobNextStep`): Feeds combinations of `paid`, `merchant_complete`, `customer_complete`, and `status` into `jobNextStep` to verify that both the customer and the artisan see the exact right action prompt at every stage (for example: 'The artisan marked the work as done. Check the work, then confirm completion below.').
  • Status Label Normalization (`status-labels`): Asserts that backend status codes like `in_progress`, `en_route`, and `superseded` map to human-readable labels, and unknown codes strip underscores gracefully.

Layer 2: Component States (`src/test/components.test.tsx`)

The second layer uses React Testing Library (`render`, `screen`, `fireEvent`) to test UI components the exact way a real user—and assistive technology—experiences them:

  • ChatInbox Loading, Error & Empty States: Mocks `useCachedApi` to simulate an in-flight request (`role='status'` showing 'Loading messages…'), a network failure (`role='alert'` displaying the error and verifying that clicking 'Try again' invokes `refetch()`), and an empty inbox (`'No messages yet. Open an accepted job to start a chat.'`).
  • ChatInbox Populated State & UUID Leak Prevention: Passes a realistic chat payload containing both a raw UUID (`artisan: 'aaaaaaaa-...'`) and `artisan_name: 'Ashley night John'` with `unread_messages_count: 3`. The test asserts that the participant's human name, trade ('Hair braiding'), and unread badge (`3`) render while strictly verifying the raw UUID string never leaks onto the screen.
  • ChatAvatar Fallback & Broken Image Recovery: Renders `<ChatAvatar />` with a default brand logo path and verifies it ignores the placeholder logo in favor of initials (`'AJ'`). Then it renders an avatar with a broken photo URL, dispatches `fireEvent.error(img)`, and confirms the component swaps the broken `<img>` tag for the user's initials (`'CO'`).

Layer 3: Server Route & API Client Boundary (`src/test/api-route-handler.test.ts`)

The third layer tests how requests and responses behave at the network and SSR boundary:

  • SSR Error Boundary Interception (`src/server.ts`): Invokes `server.fetch(request)` directly to verify that a normal `200` JSON payload passes through untouched, while an unhandled h3 `500` JSON response (`{"unhandled":true,"message":"HTTPError"}`) is intercepted and transformed into a clean `500 text/html` error page ('This page didn't load') instead of dumping raw JSON in the browser.
  • 401 Token Refresh & Multi-Page Pagination (`createApiClient`): Stubs `fetch` to return `401 Unauthorized` on an expired access token, verifies the API client automatically calls `/auth/refresh/` once, updates the session token in storage, retries `/jobs/` with the fresh token, and follows the `next` cursor URL across page 1 and page 2 to return the merged dataset.
my take ↓

Anyway, that's what I've been thinking about lately. Back to building.

From the archive

Read something else.