> ## 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.

# Build a feature, part 1: register, model and test

> Add a domain feature to a GatoJS project: create the feature folder, register it in projectModules, add a Prisma model scoped by organizationId and write failing tests before any code.

This tutorial adds a small domain feature to a GatoJS project: **organization notes**. By the end of part 2 you will have a `notes` feature with a `notes` table, a `/notes` page with a list and a form, a `listNotesQuery` query, a `createNoteCommand` command and tests that prove one organization cannot see or write another organization's notes.

Part 1 (this page) covers steps 1–6: registering the feature, the database schema, contracts and the tests that are red before the implementation exists. [Part 2](https://docs.gatojs.com/guides/finish-a-feature.md) covers the query, command, component, page, the quality gates and the commit.

> [!NOTE]
>
> This tutorial builds a **project feature**: code that lives in one application. If you want to write a module that ships to many projects through the kit, see [New kit module](https://docs.gatojs.com/contributing/new-kit-module.md).

## What you will build

| File | Step | Written by |
| - | - | - |
| `src/features/notes/module.ts`, `src/features/notes/i18n/en.json`, `src/features/notes/i18n/pl.json` | 2 | You |
| `.wa/kit.json` (a `notes` entry in `projectModules`) | 3 | You |
| `src/modules.generated.ts`, `src/modules.client.generated.ts`, the `wa:relations` region in `prisma/schema/organizations.prisma` | 3 | `gato generate` |
| `prisma/schema/notes.prisma` | 4 | You |
| `prisma/migrations/<timestamp>_add_notes/migration.sql` | 4 | Prisma |
| `src/features/notes/contracts/note.schemas.ts`, `note.types.ts` | 5 | You |
| `create-note-command.test.ts`, `notes-isolation.integration.test.ts` | 6 | The test author |
| Query, command, component, page | 7 | The implementer ([part 2](https://docs.gatojs.com/guides/finish-a-feature.md)) |

```mermaid theme={null}
flowchart TD
    s1["1. Project ready"] --> s2["2. module.ts and translations"]
    s2 --> g1{"generate"}
    g1 -->|"no changes: feature not registered"| s3["3. notes entry in projectModules"]
    s3 --> g2{"generate"}
    g2 -->|"registry and wa:relations"| s4["4. notes.prisma, migration, db:generate"]
    s4 --> s5["5. Contracts: Zod schema and type"]
    s5 --> s6["6. Tests before code: red"]
    s6 --> s7["7. Query, command, component, page: green"]
    s7 --> s8["8. Gates: verify, integration, mutation"]
    s8 --> s9["9. Commit"]
```

A few terms used throughout:

* **Feature**: a folder `src/features/<name>/` holding the code of one feature.
* **Module**: an entry in `.wa/kit.json` with a manifest that lists the feature's files. Kit modules live under `modules`; your own features live under `projectModules`.
* **Module definition**: the feature's `module.ts`, created with `defineModule(...)`.
* **Module registry**: the generated files `src/modules.generated.ts` and `src/modules.client.generated.ts`. The menu, the page guard and the translation loader learn about features only through them. See [Module registry](https://docs.gatojs.com/concepts/module-registry.md).

## Step 1. Start from a working project

Your project should already be set up as in the [Quickstart](https://docs.gatojs.com/quickstart.md): dependencies installed, `.env` in place, the database running in Docker, the `init` migration applied and the first account created. Before you continue, check three things, because each one breaks a later step:

1. **Database port.** If you changed `DB_PORT` in `.env`, the port in `DATABASE_URL` must match.
2. **Migrations are committed.** `git ls-files prisma/migrations` should list `migration_lock.toml` and the `init` migration. An empty result means migrations are ignored; see [Database and migrations](https://docs.gatojs.com/guides/database-and-migrations.md).
3. **A clean branch.** Start on a feature branch, for example `git switch -c feat/notes`.

## Step 2. Feature folder, module definition and translations

The feature lives in `src/features/notes/`. The folder name is also the translation namespace, and the menu looks up its label under the module `key`, so **`key` must equal the folder name**. Nothing checks this: with `key: "note"` in a `notes` folder, the menu shows the raw translation key instead of a label.

```ts src/features/notes/module.ts theme={null}
import { defineModule } from "@/shared/lib/modules/define-module";

export default defineModule({
  key: "notes",
  nav: [{ href: "/notes", labelKey: "nav", icon: "notebook-pen", order: 50 }],
  routePrefixes: ["/notes"],
});
```

* `nav` adds one menu item. `icon` is a [lucide](https://lucide.dev/icons) icon name, and `order: 50` places it between Dashboard (10) and Users (80).
* `routePrefixes` is required by the type but does **not** protect the route. The page is protected by `requireModuleAccess("notes")`, which you add in part 2.
* Without `roles`, `adminOnly` or `public`, every role in the organization can access the feature. The optional `auditActions`, `apiScopes` and `uploadPurposes` only matter in projects with the [audit logs](https://docs.gatojs.com/modules/audit-logs.md), [API keys](https://docs.gatojs.com/modules/api-keys.md) or [uploads](https://docs.gatojs.com/modules/uploads.md) modules.
* `module.ts` ends up in the browser bundle through the menu, so it must not import server code.

Add the feature's strings. Keys are lowercase with hyphens:

```json src/features/notes/i18n/en.json theme={null}
{
  "nav": "Notes",
  "page-title": "Notes",
  "page-description": "Notes are visible to every member of the organization.",
  "empty": "No notes yet.",
  "title-label": "Title",
  "title-placeholder": "e.g. Client meeting",
  "error-title-required": "Enter a title between 1 and 200 characters",
  "submit": "Add note",
  "submitting": "Saving...",
  "toast-created": "Note added.",
  "toast-create-error": "Could not add the note."
}
```

Create a translation file for every locale listed in `locales` in `.wa/kit.json` (by default `pl` and `en`), with the same set of keys. The architecture test `i18n-keys-exist-in-every-locale` fails `npm run verify` if a key is missing in one of them. See [Internationalization](https://docs.gatojs.com/guides/i18n.md).

Now run the generator, as you do after adding a module definition or a translation file:

```bash theme={null}
npx gato generate
```

The output is `Bez zmian` ("no changes"), and the registry files do not mention `notes`. That is expected: the generator only registers features matched by a file pattern in a manifest in `.wa/kit.json`. You add that entry in step 3.

> [!NOTE]
>
> The kit's CLI and many of its server-side messages are currently in Polish. `Bez zmian` means "no changes" and `zmieniono <file>` means "changed `<file>`".

### What a missing `projectModules` entry looks like

If a feature has files but no entry, this is what you see:

| Where | What you see | Why |
| - | - | - |
| `npx gato generate` | `Bez zmian`; `notes` is not in the registry. | The generator only reads `src/features/<x>/` patterns from the manifests in `.wa/kit.json`. |
| Menu | No "Notes" item. | The menu only walks module definitions from the registry. |
| `/notes` | Next.js "404 This page could not be found", even for admins and superadmins. | `requireModuleAccess("notes")` finds no definition and calls `notFound()`. |
| `createNoteCommand` | The command's default error message and an `error` entry in the log. | `notFound()` thrown inside `try` reaches `handleCommandError` like any unknown error. |
| Prisma, once `notes.prisma` exists | ``The relation field `organization` on model `Note` is missing an opposite relation field on the model `Organization`.`` | Only the generator writes the back-relation into `Organization`, from the entry's `schemaRelations`. |

The page guard explains the 404: a key outside the registry is rejected before roles are even considered.

```ts src/shared/lib/auth/require-module-access.ts theme={null}
export async function requireModuleAccess(
  moduleKey: string,
): Promise<OrgContext> {
  const context = await resolveOrgContext();
  const moduleDef = moduleByKey(moduleKey);
  const allowed =
    moduleDef !== null &&
    canAccessModule(moduleDef, {
      userRole: context.userRole,
      orgRole: context.orgRole,
      multiOrg: env.MULTI_ORG,
    });
  if (!allowed) {
    notFound();
  }
  return context;
}
```

## Step 3. Add the entry to `projectModules`

`.wa/kit.json` has two module sections. `modules` describes code your project received from the kit, with versions and file hashes used by updates. `projectModules` describes features written in your project: an entry has only a `manifest`, with no version tracking or hashes, and `gato generate` reads it exactly like a kit module. Project modules are registered after kit modules, in alphabetical order. The full format is in the [`.wa/kit.json` reference](https://docs.gatojs.com/cli/kit-json).

Add a `notes` entry:

```json .wa/kit.json theme={null}
{
  "kitVersion": "0.8.1",
  "kitRepo": "https://github.com/webamigos/gatojs.git",
  "project": { "name": "Acme CRM", "slug": "acme-crm" },
  "locales": ["pl", "en"],
  "modules": {
    "...": "kit modules, unchanged"
  },
  "projectModules": {
    "notes": {
      "manifest": {
        "name": "notes",
        "version": "0.1.0",
        "description": "Project feature: organization notes",
        "requires": [],
        "files": [
          "src/features/notes/**",
          "src/app/[locale]/(app)/notes/**",
          "prisma/schema/notes.prisma"
        ],
        "dependencies": {},
        "devDependencies": {},
        "env": [],
        "schemaRelations": [
          { "model": "Organization", "field": "notes Note[]" }
        ],
        "compose": null,
        "ciSteps": null,
        "workspaces": []
      }
    }
  }
}
```

When reading the file, the generator enforces four rules on top of the schema, and stops with an error if one fails:

* the entry key equals `manifest.name`;
* the name is not in both `modules` and `projectModules`;
* every module in `requires` exists in `modules` or `projectModules`;
* `files` contains a pattern starting with `src/features/<name>/`.

| Field | Meaning for `notes` |
| - | - |
| `files` | The generator only reads patterns starting with `src/features/<name>/`; `src/features/notes/**` is what registers the feature. The other patterns document ownership. Use one plain pattern per feature: a pattern with braces `{…}` is silently skipped. |
| `schemaRelations` | `notes Note[]` is written into the `wa:relations` region of the `Organization` model. This is the only way to add a back-relation to a core model. Only `User` and `Organization` are supported; other models are skipped silently. |
| `env`, `compose`, `ciSteps` | Empty: the feature has no environment variables, Docker services or extra CI steps. |
| `name` | Must equal the entry key. |
| `version` | Any non-empty string. It becomes the module version if the feature is ever promoted to the kit. |
| `requires` | Kit or project modules this feature depends on. |
| `description`, `workspaces`, `dependencies`, `devDependencies` | Not used by `generate`; they only need to pass the schema. |

> [!WARNING]
>
> A typo in a field name, such as `schemaRelation`, raises no error. The field falls back to its default and the relation never appears.

Run the generator again:

```bash theme={null}
npx gato generate
```

```text theme={null}
zmieniono src/modules.generated.ts
zmieniono src/modules.client.generated.ts
zmieniono prisma/schema/organizations.prisma
```

The registry now imports the `notes` module definition and its translations after the kit modules, and the `Organization` model contains the relation:

```ts src/modules.client.generated.ts theme={null}
import notesModule from "@/features/notes/module";
// …
export const clientModules = [accountModule, authModule, dashboardModule, organizationsModule, usersModule, notesModule];
```

```prisma prisma/schema/organizations.prisma theme={null}
  // wa:relations:start
  notes Note[]
  // wa:relations:end
```

### Prisma errors between steps 3 and 4

The back-relation is added only through `schemaRelations` and the generator. Three errors can show up along the way:

* **Entry before the schema file** (the order in this tutorial). The region references a `Note` model that does not exist yet, so any Prisma command that loads the schema fails with `Type "Note" is neither a built-in type, nor refers to another model, composite type, or enum.` Don't run Prisma until you've saved the schema file from step 4.
* **Schema file before the entry.** Prisma reports the missing back-relation and suggests ``Either run `prisma format` or add it manually.`` Do neither: add `schemaRelations` and run the generator.
* **After `prisma format` or a manual edit.** `prisma format` writes `notes Note[]` below `// wa:relations:end`, outside the region. The next generator run adds the same line inside the region and the schema fails with `Field "notes" is already defined on model "Organization".` Delete the line outside the region.

Core tests don't change when you add a feature. They compare the registry only against the five core modules, while `registry-consistency.test.ts` checks the whole registry, including `notes`. Part 2 covers this in [verify and the core tests](https://docs.gatojs.com/guides/finish-a-feature.md#npm-run-verify-and-the-core-tests).

## Step 4. Schema and migration

Put the `Note` model in its own schema file. Features never edit core schema files.

```prisma prisma/schema/notes.prisma theme={null}
model Note {
  id             String   @id @default(cuid())
  organizationId String   @map("organization_id")
  title          String
  createdAt      DateTime @default(now()) @map("created_at")

  organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)

  @@index([organizationId])
  @@map("notes")
}
```

* **Required `organizationId` with an index and a relation to `Organization`.** Core domain tables look the same. Every query filters by this column, so it needs an index, and a required column means a note cannot be saved without an organization. Because the model has `organizationId`, the kit's runtime tenant-scope guard covers it automatically: a `findMany` without an organization filter throws `TenantScopeError`. See [Organizations](https://docs.gatojs.com/concepts/organizations.md).
* **`onDelete: Cascade`.** Deleting an organization deletes its notes. The foreign key to `organizations` also means `resetDatabase()` in integration tests clears the `notes` table, because `TRUNCATE … CASCADE` follows foreign keys.
* **`@map` and `@@map`.** Columns and tables use `snake_case`, like the core.

Create the migration and regenerate the Prisma client:

```bash theme={null}
npx prisma migrate dev --name add-notes
npm run db:generate
```

`migrate dev` prints a `Datasource "db": …` line (check the database name and port there), then:

```text theme={null}
Applying migration `20261028044413_add_notes`

The following migration(s) have been created and applied from new schema changes:

prisma/migrations/
  └─ 20261028044413_add_notes/
    └─ migration.sql

Your database is now in sync with your schema.
```

Your timestamp will differ. The generated SQL:

```sql prisma/migrations/20261028044413_add_notes/migration.sql theme={null}
-- CreateTable
CREATE TABLE "notes" (
    "id" TEXT NOT NULL,
    "organization_id" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "notes_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "notes_organization_id_idx" ON "notes"("organization_id");

-- AddForeignKey
ALTER TABLE "notes" ADD CONSTRAINT "notes_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
```

> [!WARNING]
>
> In Prisma 7, `migrate dev` does not generate the client. Without `npm run db:generate`, TypeScript does not know the model: `npx tsc --noEmit` fails with `error TS2339: Property 'note' does not exist on type 'PrismaClient'.`

Commit the migration folder together with the feature: production only applies migrations that are in the repository.

## Step 5. Contracts

Contracts are the input schema and the result type. They come before tests because tests and code both depend on them, and because the browser form and the server command validate against the same schema.

```ts src/features/notes/contracts/note.schemas.ts theme={null}
import { z } from "zod";

export const createNoteSchema = z.object({
  title: z.string().trim().min(1).max(200),
});

export type CreateNoteValues = z.infer<typeof createNoteSchema>;
```

```ts src/features/notes/contracts/note.types.ts theme={null}
export interface NoteListItem {
  id: string;
  title: string;
  createdAt: Date;
}
```

`trim()` turns a whitespace-only title into an empty string, which then fails `min(1)`. `z.object` strips unknown keys, so an `organizationId` sent from the browser never reaches `parsed.data`. Still, what protects writes to another organization is not the schema but taking `organizationId` from the server-side context in the command (part 2). Validation messages are Zod's defaults, for example `Too small: expected string to have >=1 characters`. The form shows its own translated message; the server message is only visible to requests that bypass the form.

## Step 6. Tests before code

GatoJS expects tests for a task to be written **before** the implementation, ideally by a different author than the code. A test written after the code by the same author tends to restate the code's assumptions and pass. With AI agents, the kit ships a dedicated `test-writer` agent for this; see [Built for AI agents](https://docs.gatojs.com/guides/ai-agents.md). Working alone, keep at least the order: plan, tests, then code.

### Plan behaviors and the mutations to kill

Start from a list of behaviors (input → literal expected result) and the code mutations each test must catch:

| Behavior | Mutation the test must kill |
| - | - |
| Member of `org-1`, `{ title: "Client meeting" }` → `{ success: true, data: { noteId: "note-1" } }`, write `{ organizationId: "org-1", title: "Client meeting" }` | wrong key in `requireModuleAccess`, no write |
| `{ title: "Plan", organizationId: "org-2" }` → write with `organizationId: "org-1"` | `organizationId` taken from input instead of context |
| `"  Sprint plan  "` → write `"Sprint plan"` | no `trim` |
| Empty, whitespace-only, 201-character, missing, numeric or `null` title → `success: false`, no write | no validation, wrong limit |
| No session or no active organization → redirect, no write | Prisma called before the guard |
| Service mode without confirmation, or confirmed for another organization → service-mode error, no write | `assertServiceModeConfirmed` removed |
| Database error → the command's default message | technical error leaked to the user |
| Success → `revalidatePath("/notes")`; failure → no revalidation | revalidation missing |

The isolation test has its own behaviors: organization A's list contains none of B's notes, a command with A's context writes to A, passing B's `organizationId` in the input does not move the note, and user A with B as the active organization is redirected and writes nothing.

### Red for the right reason

Before the implementation, tests must fail because an export is missing or a value is wrong, not because of an import error. If the command file doesn't exist, Vitest only reports:

```text theme={null}
Error: Failed to resolve import "../create-note-command" from "src/features/notes/services/commands/__tests__/create-note-command.test.ts". Does the file exist?
```

So create empty stubs first. The command file contains `"use server";` and `export {};`; the query file contains `import "server-only";` and `export {};`. Now every test fails for the right reason, for example `TypeError: createNoteCommand is not a function`.

> [!TIP]
>
> When AI agents do the implementation, write `implement` to `.superpowers/phase` in the implementer's working copy before it starts. The `protect-tests` hook then blocks edits to test files. See [Built for AI agents](https://docs.gatojs.com/guides/ai-agents.md#the-implementation-phase-and-the-protect-tests-hook).

### Command unit test

Mock only inputs and outputs: Prisma, the session context (`getOrgContext`), configuration (`env`), the logger, the locale, and Next.js `notFound`, `redirect` and `revalidatePath`. Keep `requireModuleAccess`, the module registry, `assertServiceModeConfirmed` and `handleCommandError` real: those are the rules under test.

```ts src/features/notes/services/commands/__tests__/create-note-command.test.ts theme={null}
const { mockPrisma, mockGetOrgContext, mockLogger, NoOrganizationError } =
  vi.hoisted(() => ({
    mockPrisma: { note: { create: vi.fn() } },
    mockGetOrgContext: vi.fn(),
    mockLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
    NoOrganizationError: class NoOrganizationError extends Error {},
  }));

vi.mock("@/shared/lib/prisma", () => ({ prisma: mockPrisma }));
vi.mock("@/shared/lib/auth/org-context", () => ({
  NoOrganizationError,
  getOrgContext: () => mockGetOrgContext(),
}));
vi.mock("@/env", () => ({ env: { MULTI_ORG: false } }));
vi.mock("@/shared/lib/logger", () => ({ logger: mockLogger }));
vi.mock("next-intl/server", () => ({ getLocale: async () => "en" }));
vi.mock("next/navigation", () => ({
  notFound: () => {
    throw Object.assign(new Error("NEXT_HTTP_ERROR_FALLBACK;404"), {
      digest: "NEXT_HTTP_ERROR_FALLBACK;404",
    });
  },
}));
vi.mock("@/i18n/routing", () => ({
  redirect: ({ href }: { href: string }) => {
    throw Object.assign(new Error("NEXT_REDIRECT"), {
      digest: `NEXT_REDIRECT;replace;${href};307;`,
    });
  },
}));
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
```

* **Mock `env`.** `requireModuleAccess` reads `env.MULTI_ORG`, and the first read of `env` validates every core variable. The CI `verify` job has no `.env`, so the real `env` would fail there even though the test passes locally.
* **Errors carry a `digest`.** `handleCommandError` recognizes a redirect by a `digest` starting with `NEXT_REDIRECT`, just like Next.js. A mock without `digest` would turn the redirect into a default error message, and the test would check behavior the app doesn't have.

Two tests from the file. Expected values are literals:

```ts src/features/notes/services/commands/__tests__/create-note-command.test.ts theme={null}
  it("ignores organizationId from the input and writes to the context organization", async () => {
    await createNoteCommand({ title: "Plan", organizationId: "org-2" });

    expect(createdData()).toEqual({ organizationId: "org-1", title: "Plan" });
  });
// …
  describe("service mode", () => {
    beforeEach(() => {
      mockGetOrgContext.mockResolvedValue(SERVICE_CONTEXT);
    });

    it("without confirmation → service-mode error and no write", async () => {
      const result = await createNoteCommand({ title: "Plan" });

      expect(result).toEqual(SERVICE_MODE_ERROR);
      expectNoWrite();
    });
```

`createdData()` returns the `data` of the first `prisma.note.create` call, and `expectNoWrite()` asserts there was no write and no `revalidatePath`. `SERVICE_CONTEXT` is a superadmin context with `serviceMode: true`, and `SERVICE_MODE_ERROR` is the literal `{ success: false, error: "Potwierdź zmianę w trybie serwisowym" }`, the message thrown by the kit's `assertServiceModeConfirmed`. Service mode is explained in [Superadmin and service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md).

### Isolation test on a real database

A unit test with a mocked Prisma cannot notice a missing `organizationId` filter, because the mock returns whatever the test prepared. Only a test against real Postgres with two organizations can. Copy the session stubs, the `vi.mock` calls and `signInAs` from `src/features/organizations/services/__tests__/organization-isolation.integration.test.ts` (the [Testing guide](https://docs.gatojs.com/guides/testing.md#organization-isolation-test) walks through them), with two changes:

```ts src/features/notes/services/__tests__/notes-isolation.integration.test.ts theme={null}
vi.mock("@/i18n/routing", () => ({
  redirect: vi.fn(({ href }: { href: string }) => {
    throw Object.assign(new Error("NEXT_REDIRECT"), {
      digest: `NEXT_REDIRECT;replace;${href};307;`,
    });
  }),
}));
vi.mock("@/shared/lib/auth", () => ({
  auth: { api: { getSession: vi.fn(readMockedSession) } },
}));
vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
```

1. **`redirect` with a `digest`.** The core test's stub throws a plain `new Error("NEXT_REDIRECT")`. That is enough there, but a command that calls `requireModuleAccess` inside `handleCommandError` would turn it into a default error.
2. **Mock `next/cache`.** Outside a Next.js request, `revalidatePath` throws `Invariant: static generation store missing in revalidatePath /notes`. The command catches it after the write, so the row is saved but the result is a failure. Assert the command result as well as the database contents, or this goes unnoticed.

Seed both organizations from literals in `beforeEach`:

```ts src/features/notes/services/__tests__/notes-isolation.integration.test.ts theme={null}
  await resetDatabase();
  currentSession.value = null;
  const alice = await createUser({ email: "alice@a.example" });
  const bob = await createUser({ email: "bob@b.example" });
  const orgA = await createOrganization({
    name: "Org A",
    createdAt: new Date("2026-01-01T00:00:00.000Z"),
    members: [{ userId: alice.id, role: "owner" }],
  });
  const orgB = await createOrganization({
    name: "Org B",
    createdAt: new Date("2026-02-01T00:00:00.000Z"),
    members: [{ userId: bob.id, role: "member" }],
  });
  await prisma.note.create({
    data: {
      organizationId: orgA.id,
      title: "A: first",
      createdAt: new Date("2026-03-01T10:00:00.000Z"),
    },
  });
// …
  world = { alice, bob, orgA, orgB };
```

The write test compares both organizations with literals. `titlesIn(org)` reads an organization's note titles directly through `prisma`, sorted alphabetically:

```ts src/features/notes/services/__tests__/notes-isolation.integration.test.ts theme={null}
  it("organization B's id in the input → the note still goes to A", async () => {
    await signInAs(world.alice, world.orgA);

    const result = await createNoteCommand({
      title: "A: smuggled",
      organizationId: world.orgB.id,
    });

    expect(result.success).toBe(true);
    await expect(titlesIn(world.orgB)).resolves.toEqual(["B: only"]);
    await expect(titlesIn(world.orgA)).resolves.toEqual([
      "A: first",
      "A: second",
      "A: smuggled",
    ]);
  });
```

### Run the tests

```bash theme={null}
npx vitest run src/features/notes/services/commands/__tests__/create-note-command.test.ts
npm run test:integration -- src/features/notes/services/__tests__/notes-isolation.integration.test.ts
```

`npx vitest run` skips `*.integration.test.ts`, so the isolation test needs `npm run test:integration`. Without `INTEGRATION_DATABASE_URL`, it connects to `postgresql://postgres:postgres@localhost:5432/wa_app_test`. If your database runs on another port, set the variable **in the shell** (an entry in `.env` is not read):

```bash theme={null}
INTEGRATION_DATABASE_URL=postgresql://postgres:postgres@localhost:5439/wa_app_test npm run test:integration -- src/features/notes/services/__tests__/notes-isolation.integration.test.ts
```

> [!WARNING]
>
> Integration tests wipe their database. The only safeguard is that the database name must end in `_test`; the host and port are not checked. Read [Commands that reset a database](https://docs.gatojs.com/guides/testing.md#commands-that-reset-a-database) before the first run.

Before the implementation, both runs are red with `TypeError: … is not a function`. That is the state you want at the end of part 1.

## Next

Continue with [part 2](https://docs.gatojs.com/guides/finish-a-feature.md): the query, command, component and page that turn these tests green, then `npm run verify`, integration and mutation tests, and the commit.


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