# Testing server code: Server Components, Server Actions, loaders

The server half of a React app is plain async functions. Test them as functions; keep the DOM assertions for what the client renders. Open this when the code under test has `async function Page`, `'use server'`, `'use cache'`, or a `loader`/`action` export.

Sources: https://nextjs.org/docs/app/guides/testing/vitest · https://reactrouter.com/start/framework/data-loading

## 1. Async Server Components

An async Server Component is an async function that returns JSX. Await it, then render the result with React Testing Library. In Next.js 16 `params` and `searchParams` are promises.

```tsx
import { render, screen } from '@testing-library/react';
import OrderPage from '@/app/orders/[id]/page';

vi.mock('@/lib/orders', () => ({ getOrder: vi.fn(async () => ({ id: '42', total: 10 })) }));

it('renders the order number', async () => {
  const ui = await OrderPage({ params: Promise.resolve({ id: '42' }) });
  render(ui);
  expect(screen.getByRole('heading', { name: /order #42/i })).toBeInTheDocument();
});
```

Limits worth stating to the user: this exercises the component's own output, not streaming, not Suspense boundaries above it, and not any nested async child (React does not resolve those outside a server renderer). If the page composes several async children, test the data functions directly and cover the composed page with one Playwright test instead.

## 2. Server Actions

A Server Action is an async function with a `'use server'` directive. Import it and call it with `FormData`. The directive has no runtime effect outside the Next.js build, so nothing special is needed — except that `cookies()` and `headers()` only exist in a request scope, so mock them.

```ts
import { createOrder } from '@/app/orders/actions';

vi.mock('next/headers', () => ({
  cookies: async () => ({ get: (k: string) => (k === 'session' ? { value: 'u_1' } : undefined) }),
  headers: async () => new Headers({ 'x-forwarded-for': '127.0.0.1' }),
}));
const updateTag = vi.fn();
vi.mock('next/cache', () => ({ updateTag: (...a: unknown[]) => updateTag(...a), revalidateTag: vi.fn() }));

it('rejects an invalid email and returns field errors', async () => {
  const form = new FormData();
  form.set('email', 'nope');
  const state = await createOrder({ status: 'idle' }, form);
  expect(state).toMatchObject({ status: 'error', fieldErrors: { email: expect.any(String) } });
  expect(updateTag).not.toHaveBeenCalled();
});

it('creates the order and invalidates the tag', async () => {
  const form = new FormData();
  form.set('email', 'a@b.com');
  await createOrder({ status: 'idle' }, form);
  expect(updateTag).toHaveBeenCalledWith('orders');
});
```

Cover three things per action: the Zod validation failure, the authorisation failure (no session cookie → refused), and the success path with its cache invalidation. An action is a public endpoint; the authorisation test is not optional.

## 3. `'use cache'` functions

```ts
import { getCatalog } from '@/lib/catalog';   // file starts with 'use cache'

it('maps the API payload to catalog entries', async () => {
  server.use(http.get('https://api.example.com/catalog', () => HttpResponse.json({ data: [/* … */] })));
  await expect(getCatalog()).resolves.toEqual([{ id: '1', name: 'Bolt' }]);
});
```

Outside the Next.js build the directive is inert, so this is a unit test of the mapping logic, and memoisation, `cacheLife` and `cacheTag` are **not** exercised. Verify caching behaviour with a request-count assertion in an end-to-end test or a response-header check, never with a unit test that claims to prove a cache hit.

## 4. React Router loaders, actions and middleware

```ts
import { loader, action } from '@/routes/orders';

it('returns the orders for the signed-in user', async () => {
  const data = await loader({
    request: new Request('https://app.test/orders?status=open', { headers: { cookie: 'session=u_1' } }),
    params: {},
    context: { session: { userId: 'u_1' } },
  } as never);
  expect(data.orders).toHaveLength(2);
});

it('redirects anonymous users', async () => {
  const res = await action({ request: new Request('https://app.test/orders', { method: 'POST' }), params: {}, context: {} } as never)
    .catch((r: Response) => r);            // redirect() throws a Response
  expect((res as Response).status).toBe(302);
});
```

`redirect()` and `data()` return or throw real `Response` objects — assert on `status` and `headers.get('location')`, not on a mock.

## 5. What belongs in an end-to-end test instead

- Streaming order and Suspense fallbacks actually appearing.
- Cache hits, revalidation after an action, and stale content after a deploy.
- Cookie/session flow across a redirect.
- Anything whose correctness depends on the framework's runtime rather than your code.

One Playwright journey per critical path covers all of these; duplicating them in unit tests produces confident tests that prove nothing.
