> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Testing

> How GatoJS tests your app: Vitest unit tests, integration tests on real Postgres, Playwright end-to-end tests and Stryker mutation testing, plus database safety and organization isolation tests.

Every GatoJS project ships with four kinds of tests already wired up. Each one replaces a different part of the system, so each catches different bugs. A unit test with a mocked Prisma checks the order of steps in a command, but it will never notice a missing `organizationId` filter, because the mock returns whatever the test prepared regardless of `where`. Only an integration test on a real database with two organizations catches that.

## Test types

| Type | Real vs. replaced | Location | Command | Database | In `npm run verify` |
| - | - | - | - | - | - |
| Unit and component | Real function or React component in jsdom. Replaced: Prisma, the better-auth session, Next.js, mail. | `__tests__/` next to the code | `npm test` | no | yes |
| Architecture | The project's real files on disk: guards before Prisma, agent instructions, translations, `.env.example`, client imports. | `src/__tests__/` | `npm test` | no | yes |
| Integration | Real Postgres, Prisma, queries, commands and guards (and MinIO for the `uploads` module). Replaced: Next.js headers and redirects, the next-intl locale, `auth.api.getSession`. | `*.integration.test.ts` | `npm run test:integration` | `_test`, truncated | no |
| End-to-end | The whole app after a production build, Chromium, the database and mailpit. Nothing replaced. | `e2e/*.spec.ts` | `npm run test:e2e` | `_e2e`, dropped | no |
| Claude Code hooks | The hook scripts in `.claude/hooks/`, also as separate processes. | `.claude/hooks/*.test.mjs` | `npm run test:hooks` | no | yes |
| Mutation (Stryker) | Unit or integration tests run against code with deliberately injected bugs. | config in the repo root | `npm run test:mutation` and related | integration run: `_test`, truncated | no |

`npm run verify` is the gate you run before handing in work: lint, typecheck, `npm test`, the production build, workspace package checks and hook tests. It does **not** run integration, e2e or mutation tests, because they need a database or a browser, and a full mutation run takes about an hour. Integration and e2e tests run in separate CI jobs; mutation tests run locally or when you trigger the workflow manually. So before you hand in a change to a query, a command or the sign-in flow, run them yourself.

## Unit and component tests

`npm test` runs Vitest with `vitest.config.ts`:

* **jsdom environment** so component tests can render React. A file that needs plain Node starts with `// @vitest-environment node`.
* **`vitest.setup.ts`** adds the Testing Library DOM matchers (such as `toBeInTheDocument`) and loads `.env.local` and `.env`. Tests see `DATABASE_URL` but never connect, because Prisma is replaced.
* **Files:** `src/**/*.test.ts(x)`, `scripts/**/*.test.ts` and `e2e/**/*.test.ts`, plus project packages in `packages/*/src`. `*.integration.test.ts` files are excluded.
* **`globals: true`** gives you `describe`, `it` and `expect` without imports; **`clearMocks: true`** resets mock call history before each test.
* **`server-only` is aliased** to an empty module, so server files can be imported in tests.

Replace only inputs and outputs: Prisma, mail, the network and better-auth's `auth.api`. Keep the file containing the security rule under test real. If you mock the file that checks the admin role, the test can no longer see that rule.

There are two ways to replace Prisma:

* **`vi.mock("@/shared/lib/prisma", …)`** with `vi.fn()` functions, when the test checks the order of steps and the data passed (see `src/features/users/services/commands/__tests__/invite-user-command.test.ts`).
* **`createFakePrisma`** from `src/test/fake-prisma.ts`, when the test must prove that `where` really filters. It is an in-memory Prisma for the `users`, `organizations`, `members` and `sessions` tables that evaluates `where` (`AND`, `OR`, `NOT`, `equals`, `in`, `notIn`, `not`, relation filters), `orderBy`, `select`, `include`, `take` and `skip`. An unsupported operator throws, so a test never passes silently.

Run one file with `npx vitest run <path>`, or watch mode with `npm run test:watch`.

## Integration tests

Integration tests exercise queries, commands and guards on real Postgres. They live in `*.integration.test.ts` files and are not part of `npm test`. The core has one, the organization isolation test; kit modules add their own.

`vitest.integration.config.ts`:

* `node` environment, files `src/**/*.integration.test.ts`;
* a `globalSetup` that creates the test database if missing and syncs its schema with `prisma db push`;
* a setup file that points `DATABASE_URL` at the test database and sets the variables the app needs (auth secret, `APP_URL`, `EMAIL_FROM`, `API_KEY_PEPPER`, S3 settings for MinIO, `MULTI_ORG=false`, `AUTH_PUBLIC_SIGNUP=false`);
* `fileParallelism: false`, because every file shares one database and every test starts by truncating tables;
* `testTimeout: 20_000` and `hookTimeout: 60_000`.

Helpers in `src/test/integration/database.ts`:

| Function | What it does |
| - | - |
| `resetDatabase()` | Checks the database name and truncates the core tables. |
| `createUser({ email, role? })` | Creates an account with a verified email; global role defaults to `user`. |
| `createOrganization({ name, createdAt, members })` | Creates an organization with a slug from the name and the given members and roles. |
| `createInvitation({ … })` | Creates an invitation; defaults to role `member`, status `pending`. |
| `createSession({ userId, activeOrganizationId })` | Creates a one-hour session with the given active organization. |
| `readActiveOrganizationId(sessionId)` | Reads a session's `activeOrganizationId` straight from the database. |

### Run them

**1. Start the database**

```bash theme={null}
docker compose up -d db
```

With the `uploads` module, also start MinIO and create the bucket (these services use the `s3` profile):

```bash theme={null}
docker compose --profile s3 up -d db minio minio-init
```

**2. Run the tests**

```bash theme={null}
npm run test:integration
```

The default target is `postgresql://postgres:postgres@localhost:5432/wa_app_test`, and `globalSetup` creates it if needed. If your Postgres runs on another port, set the URL **in the shell**:

```bash theme={null}
INTEGRATION_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/wa_app_test npm run test:integration
```

Vitest does not load `.env` into `process.env` here, so a value in `.env` is ignored and the tests fall back to port 5432.

**3. Check where they ran**

Prisma prints `Datasource "db": PostgreSQL database "wa_app_test", schema "public" at "localhost:5432"` first. Check the database name and port.

Run a single file with `npm run test:integration -- <path>`. Plain `npx vitest run <path>` uses the unit config, skips integration files and exits with `No test files found, exiting with code 1`.

## End-to-end tests

E2E tests check flows that involve every part at once in a browser: invitation by email, setting a password, sign-in, sign-up and creating an organization.

`npm run test:e2e`:

1. runs `npm run build` (standalone output) and copies `.next/static` into the standalone folder;
2. starts two `node .next/standalone/server.js` servers with different settings and waits for `/sign-in` to respond (up to 120 seconds);
3. runs `e2e/global-setup.ts`: checks the database name, drops and rebuilds the e2e database, creates the admin account and empties the mailpit inbox;
4. runs two Playwright projects, each against its own server.

| Project | File | Port | `MULTI_ORG` | `AUTH_PUBLIC_SIGNUP` | What it checks |
| - | - | - | - | - | - |
| `core-auth` | `e2e/core-auth.spec.ts` | `E2E_CORE_PORT`, default 3000 | `false` | `false` | Admin invites a user, who sets a password from the email and signs in; `/users` returns 404 for them. Sign-up without an invitation gets 403. Password reset. |
| `multi-org` | `e2e/multi-org.spec.ts` | `E2E_MULTI_ORG_PORT`, default 3001 | `true` | `true` | Every sign-up creates its own organization, the organization switcher appears, and the second user cannot see the first user's members. |

Tests run serially with one worker and no retries; traces are kept only for failures. Tests find elements by Polish UI labels, most of them in the `LABELS` constant in `e2e/helpers.ts`.

### Before the first run

**1. Start the database and mailpit**

`docker compose up -d`. The `wa_app_e2e` database is created by Prisma.

**2. Install Chromium once**

```bash theme={null}
npx playwright install chromium
```

**3. Free ports 3000 and 3001**

Stop `npm run dev`. Playwright doesn't reuse a running server and fails before touching the database if a port is busy. Use `E2E_CORE_PORT` and `E2E_MULTI_ORG_PORT` to change them.

**4. Pass custom ports in the shell**

The e2e config reads ports only from environment variables, not from `.env`:

```bash theme={null}
DB_PORT=5433 MAILPIT_UI_PORT=8026 MAILPIT_SMTP_PORT=1026 npm run test:e2e
```

> [!NOTE]
>
> Prisma refuses `db push --force-reset` and `migrate reset` when it detects it was started by an AI agent (for example inside Claude Code), unless `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` is set. So `npm run test:e2e` launched by an agent stops at the database reset. Run e2e tests yourself, or let an agent run them only with your explicit consent. Integration tests usually work under an agent, because a plain `prisma db push` only asks when a schema change would drop data.

## Commands that reset a database

> [!WARNING]
>
> Integration and e2e tests delete data in their database on every run. The **only** safeguard is the database name: integration tests run only on a database whose name ends in `_test`, e2e tests only on one ending in `_e2e`. The host and port are **not** checked. Your development database `wa_app` is safe, but any other database with one of those suffixes, including one in another project's Postgres, will be wiped.

| Command | What it does to the database | Which database | Safeguard |
| - | - | - | - |
| `npm run test:e2e` | Once per run: `prisma db push --force-reset`, or `prisma migrate reset --force` when `prisma/migrations/` contains a migration. Both delete all data and schema. | `DATABASE_URL` from the shell, otherwise `postgresql://postgres:postgres@localhost:$DB_PORT/wa_app_e2e` (port defaults to 5432). | Name must end in `_e2e`, checked before the reset. |
| `npm run test:integration` | Once per run: `CREATE DATABASE` if missing and `prisma db push`. Then `resetDatabase()` before tests: `TRUNCATE` of the core tables and every table with a foreign key to them. | `INTEGRATION_DATABASE_URL` from the shell, otherwise `postgresql://postgres:postgres@localhost:5432/wa_app_test`. `DB_PORT` has no effect. | Name must end in `_test`, checked in `globalSetup` and in every `resetDatabase()`. |
| `npm run test:mutation:integration` | Like `test:integration`, but many times. | Same. | Same. |
| `npx prisma migrate reset`, `npx prisma db push --force-reset` run by hand | Delete all data. | `DATABASE_URL` from the shell or `.env`, usually `wa_app`. | None. `migrate reset` without `--force` asks first. |

`npm test`, `npm run verify`, `npm run test:hooks`, `npm run test:mutation`, `npm run test:mutation:task` and `npm run test:mutation:gate` never touch a database.

What the name check does not cover:

* **The server.** Every GatoJS project uses the same default names `wa_app_test` and `wa_app_e2e`, and both commands default to port 5432. If you moved your Postgres to another port because 5432 belongs to another project, and didn't pass the port in the shell, the tests will wipe *that* project's test database. Check `echo "$DB_PORT $DATABASE_URL $INTEGRATION_DATABASE_URL"` before running.
* **What the database is for.** Any name with the suffix passes, such as `orders_test`. Don't give those names to databases you want to keep.
* **Manual Prisma commands**, which work on `DATABASE_URL` with no name check.

The e2e setup also deletes every email from mailpit at `MAILPIT_URL` (default `http://localhost:8025`), which is the same mailpit `npm run dev` sends to.

## Organization isolation test

Prisma does not filter by organization on its own. Every query and command adds the `organizationId` filter from `getOrgContext()`, and the kit's runtime tenant-scope guard throws when a scoped model is queried without one. What neither the guard nor a mocked unit test can tell you is whether the filter uses the **right** organization. That takes a test on real Postgres with two organizations, and the project rules require one for every new query and command on domain data. See [Organizations](https://docs.gatojs.com/concepts/organizations.md) for the data model.

Add an isolation test when you add:

* a query that reads organization data;
* a command that creates, updates or deletes organization data (the most common leak is updating a record by an `id` from the input without `organizationId` in `where`);
* a change to `where` in an existing query or command;
* a fix for a leak. The test must fail without the fix.

Components and pure functions without Prisma don't need one.

### How to build one

Create a separate file such as `src/features/<x>/services/__tests__/<x>-isolation.integration.test.ts`.

**1. Copy the stubs and signInAs**

The session stub (`currentSession`, `readMockedSession` in a `vi.hoisted` block), the `vi.mock` calls and `signInAs` are defined in `src/features/organizations/services/__tests__/organization-isolation.integration.test.ts` itself, so your file needs its own copy. They replace what doesn't exist outside an HTTP request: headers, locale, `notFound`, `redirect` and `auth.api.getSession`. `signInAs` creates a real session in the database and returns it from the stub:

```ts theme={null}
vi.mock("next/headers", () => ({ headers: vi.fn(async () => new Headers()) }));
vi.mock("next-intl/server", () => ({ getLocale: vi.fn(async () => "en") }));
vi.mock("next/navigation", () => ({
  notFound: vi.fn(() => {
    throw new Error("NEXT_NOT_FOUND");
  }),
}));
vi.mock("@/i18n/routing", () => ({
  redirect: vi.fn(() => {
    throw new Error("NEXT_REDIRECT");
  }),
}));
vi.mock("@/shared/lib/auth", () => ({
  auth: { api: { getSession: vi.fn(readMockedSession) } },
}));
// …
async function signInAs(
  user: { id: string },
  organization: { id: string } | null,
  role = "user",
): Promise<{ id: string }> {
  const activeOrganizationId = organization?.id ?? null;
  const session = await createSession({
    userId: user.id,
    activeOrganizationId,
  });
  currentSession.value = {
    user: { id: user.id, role },
    session: { id: session.id, activeOrganizationId },
  };
  return session;
}
```

If your command goes through `handleCommandError`, give the `redirect` error a `digest` (`NEXT_REDIRECT;replace;<href>;307;`) and mock `next/cache`. The [feature tutorial](https://docs.gatojs.com/guides/build-a-feature.md#isolation-test-on-a-real-database) explains why.

**2. Seed two organizations in beforeEach**

Call `resetDatabase()`, create users and two organizations with the helpers, then create feature records in both organizations with literal values. Call `prisma.$disconnect()` in `afterAll`.

**3. Test the query**

Sign in as a user of organization A, call the query and compare the result with a literal that contains only A's records. Repeat for B.

**4. Test the command**

Sign in as a user of A and call the command with the `id` of a record in B. Assert that it refused (a literal `OperationResult`), then read B's record straight through `prisma` and compare it with the seeded values.

**5. Test a missing membership**

Sign in as user A with B as the active organization and assert the query throws `NoOrganizationError`.

**6. Make sure it can fail**

Temporarily point the `where` filter at the other organization and run the test. It must go red. `npm run test:mutation:integration` does this automatically for every file under `src/features/*/services/`.

Write expected values as literals (emails, names, counts), never as the output of production code.

`resetDatabase()` truncates the core tables with `CASCADE`, so a feature table with a foreign key to `organizations` or `users` is cleared too. A table without such a key must be cleared in your own `beforeEach` with `prisma.<model>.deleteMany()`.

## Mutation testing

Stryker creates mutants (copies of your code with one deliberate change, such as a flipped condition) and runs the tests covering each one. A mutant no test catches points at behavior without a test. Mutation testing is central to how GatoJS works with AI agents, so it is covered in detail in [Built for AI agents](https://docs.gatojs.com/guides/ai-agents.md#mutation-testing). The short version:

| Command | What it does |
| - | - |
| `npm run test:mutation:task -- src/a.ts,src/b.ts` | Mutates only the listed files (comma-separated, no spaces) against unit tests. Use this per task. |
| `npm run test:mutation` | Full run against unit tests. |
| `npm run test:mutation:integration` | Mutates `src/features/*/services/**` and two auth files against integration tests. Needs the `_test` database. |
| `npm run test:mutation:gate` | Fails if any critical file has an undetected mutant without an approved exception. |

Never run two Stryker processes at once: they share report files and the test database.

## Run times and CI

Indicative local timings on an 8-core machine:

| Command | Time |
| - | - |
| `npm test` | about 17 s |
| `npm run test:integration` | a few seconds for the core suite; longer with kit modules |
| `npm run test:hooks` | under 1 s |
| `npm run test:mutation:task -- <one file>` | 1–3 min |
| `npm run test:mutation:gate` | under 1 s |
| `npm run test:mutation` without an incremental file | tens of minutes; about an hour for unit and integration together |

Incremental runs are much shorter, because Stryker only retests mutants in changed code.

| Workflow, job | When | Runs | Services |
| - | - | - | - |
| `ci.yml`, `verify` | Push and pull request to `main` | `npm run wa -- generate`, `git diff --exit-code`, `npm run verify` | none |
| `ci.yml`, `integration` | Same | Steps from the `wa:ci-integration` region, then `npm run test:integration` | `postgres:16`; MinIO with the `uploads` module |
| `e2e.yml` | Push to `main`; pull requests to `main` unless they only change docs, `*.md` or `.husky/**` | Chromium install, `npx prisma migrate dev --name init`, `npm run test:e2e`; HTML report as an artifact. 30-minute limit. | `postgres:16`, mailpit |
| `mutation.yml` | Manual only (`workflow_dispatch`) | `npm run test:mutation`, `npm run test:mutation:integration`, `npm run test:mutation:gate`. 360-minute limit; incremental files cached per branch. | `postgres:16` |

Mutation tests don't run on pull requests because a full run is too slow. Run them per task locally, and the full suite before a release or by triggering **Mutation testing** in the Actions tab. More in [CI](https://docs.gatojs.com/deployment/ci.md).

## Command reference

| Command | Script | Database | In `verify` | In CI |
| - | - | - | - | - |
| `npm test` | `vitest run` | no | yes | `ci.yml`, `verify` |
| `npm run test:watch` | `vitest` | no | no | no |
| `npm run test:integration` | `vitest run -c vitest.integration.config.ts` | `_test`, truncates | no | `ci.yml`, `integration` |
| `npm run test:e2e` | build, copy static, `playwright test` | `_e2e`, drops | no | `e2e.yml` |
| `npm run test:hooks` | `node --test` on the two hook test files | no | yes | `ci.yml`, `verify` |
| `npm run test:mutation` | `stryker run` | no | no | `mutation.yml` |
| `npm run test:mutation:task -- <files>` | `stryker run --force --mutate` | no | no | no |
| `npm run test:mutation:integration` | `stryker run stryker.integration.config.json` | `_test`, truncates | no | `mutation.yml` |
| `npm run test:mutation:gate` | `tsx scripts/mutation-gate.ts` | no | no | `mutation.yml` |
| `npm run verify` | lint, typecheck, test, build, `turbo run test typecheck lint`, hook tests | no | — | `ci.yml`, `verify` |

### Test environment variables

All are read from the shell only; neither the integration config nor Playwright loads `.env`.

| Variable | Default | Notes |
| - | - | - |
| `INTEGRATION_DATABASE_URL` | `postgresql://postgres:postgres@localhost:5432/wa_app_test` | Name must end in `_test`. |
| `INTEGRATION_S3_ENDPOINT`, `INTEGRATION_S3_BUCKET` | `http://localhost:9000`, `<slug>-uploads` | MinIO for `uploads` integration tests. |
| `DATABASE_URL` (e2e) | `postgresql://postgres:postgres@localhost:$DB_PORT/wa_app_e2e` | Name must end in `_e2e`. |
| `DB_PORT` | `5432` | Only for the default e2e database URL. |
| `MAILPIT_UI_PORT`, `MAILPIT_URL` | `8025`, `http://localhost:$MAILPIT_UI_PORT` | mailpit API used by the e2e helpers. |
| `MAILPIT_SMTP_PORT`, `SMTP_URL` | `1025`, `smtp://localhost:$MAILPIT_SMTP_PORT` | SMTP for the e2e servers. |
| `E2E_CORE_PORT`, `E2E_MULTI_ORG_PORT` | `3000`, `3001` | Ports of the two e2e servers. |
| `E2E_UPLOADS_DIR` | `<system tmp>/<slug>-e2e-uploads` | Must be an absolute path. |
| `CI` | unset | Enables `forbidOnly` and the HTML reporter in Playwright. |
| `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` | unset | Your consent for a database reset started by an AI agent. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.