# Testing Guidelines

Demeter tests with **Vitest** (unit + integration) and **React Testing Library**
(web) / **React Native Testing Library** (mobile). Tests must prove **domain
correctness**, not just that code runs.

## Layers

| Layer           | Runner                                        | Scope                                                      |
| --------------- | --------------------------------------------- | ---------------------------------------------------------- |
| Unit            | `pnpm --filter @demeter/api test`             | Pure logic, route handlers with mocked deps, lib functions |
| Integration     | `pnpm --filter @demeter/api test:integration` | Real Fastify server + real `demeter_test` Postgres         |
| Performance     | `pnpm --filter @demeter/api test:perf`        | Opt-in load/throughput harness                             |
| Web a11y / unit | `pnpm --filter <web> test`                    | jsdom + Testing Library + axe-core                         |

## The integration harness

`test/integration/setup.ts` boots the **real** `buildServer()` against a
dedicated `demeter_test` database, replays the Drizzle migrations (tracking
applied files), and exposes `cleanDatabase()` (`TRUNCATE … CASCADE`) for
per-test isolation. Patterns:

- Register a fresh user per spec and use a **unique source IP** (`10.X.*`) to
  avoid the auth rate limiter tripping across tests.
- The suite **skips** if `demeter_test` is unreachable — bring up Postgres
  first.
- **Schema-reset rule:** if you edit an already-applied migration, the harness
  won't re-apply it. Reset:
  `psql "$DEMETER_TEST_DATABASE_URL" -c 'DROP SCHEMA public CASCADE; CREATE SCHEMA public;'`
- When a migration adds/removes a table, update the table-count assertion in
  `server.integration.spec.ts`.

## What a real test looks like

- Assert **specific computed values** against known-correct answers
  (`expect(total).toBe(6000)`, `expect(psnr).toBeCloseTo(32.5, 1)`), not just
  truthiness or a wide range.
- A test that still passes when the implementation returns a hardcoded/random
  value is **not** a real test — rewrite both.
- For external dependencies, inject deterministic test doubles via
  `buildServer({ verifiers, weather })` rather than calling live services (see
  [ADR-0005](../architecture/adr/0005-injectable-external-providers.md)).

## Documentation as tests

The OpenAPI reference is guarded by
`test/integration/openapi.integration.spec.ts` — a new endpoint that ships
without a summary/tag/response breaks the build. Treat schema completeness as
testable behaviour.

## Before you commit

Run the affected unit + integration suites and `npx tsc --noEmit` for the
package you touched. The pre-commit hook also type-checks affected packages
(bypass with `SKIP_TYPECHECK=1` only for docs/test-only commits).
