···11+# Test Coverage Analysis
22+33+## Current State: No Tests Exist
44+55+The monorepo has **zero test infrastructure**. No testing framework is installed, no test scripts exist in any `package.json`, and `turbo.json` has no `test` task. There are approximately **530 lines of source code** across 4 packages with 0% test coverage.
66+77+---
88+99+## Recommended Test Framework Setup
1010+1111+**Vitest** is the best fit for this project:
1212+- Native ESM support (the repo uses `"type": "module"` everywhere)
1313+- Built-in TypeScript support via `tsx`/`esbuild` (no separate ts-jest config)
1414+- Workspace-aware — can share a root config while per-package configs override as needed
1515+- Fast, with watch mode out of the box
1616+1717+### Infrastructure needed
1818+1919+1. Install `vitest` as a root devDependency
2020+2. Add a root `vitest.workspace.ts` pointing at each package
2121+3. Add `"test": "vitest run"` scripts to each package's `package.json`
2222+4. Add a `"test"` task to `turbo.json` (with `dependsOn: ["^build"]` since appview/web depend on lexicon types)
2323+5. Add `pnpm test` as a root script
2424+2525+---
2626+2727+## Package-by-Package Gaps and Recommendations
2828+2929+### 1. `@atbb/appview` — API Server (highest priority)
3030+3131+This is the most complex package (260 LOC) and where most business logic will land as stubs are implemented. It has the database schema, config loading, AT Protocol agent creation, and all API routes.
3232+3333+#### a) Route handler tests (high value)
3434+3535+**Files:** `src/routes/health.ts`, `src/routes/forum.ts`, `src/routes/categories.ts`, `src/routes/topics.ts`, `src/routes/posts.ts`
3636+3737+**What to test:**
3838+- `GET /api/healthz` returns `200` with `{ status: "ok", version: "0.1.0" }`
3939+- `GET /api/healthz/ready` returns `200` with `{ status: "ready" }`
4040+- `GET /api/forum` returns `200` with the expected forum shape
4141+- `GET /api/categories` returns `200` with `{ categories: [] }`
4242+- `GET /api/categories/:id/topics` returns `200` and echoes the `id` param
4343+- `POST /api/topics` returns `501` (not implemented)
4444+- `POST /api/posts` returns `501` (not implemented)
4545+4646+**How:** Use Hono's built-in `app.request()` test helper — no HTTP server needed:
4747+```ts
4848+import { describe, it, expect } from "vitest";
4949+import { apiRoutes } from "../src/routes/index.js";
5050+import { Hono } from "hono";
5151+5252+const app = new Hono().route("/api", apiRoutes);
5353+5454+describe("GET /api/healthz", () => {
5555+ it("returns ok status", async () => {
5656+ const res = await app.request("/api/healthz");
5757+ expect(res.status).toBe(200);
5858+ expect(await res.json()).toEqual({ status: "ok", version: "0.1.0" });
5959+ });
6060+});
6161+```
6262+6363+**Why it matters:** As stubs are replaced with real implementations, having route-level tests in place catches regressions in response shape, status codes, and content-type headers. These tests are cheap to write now and will grow in value.
6464+6565+#### b) Config loading tests (medium value)
6666+6767+**File:** `src/lib/config.ts`
6868+6969+**What to test:**
7070+- Returns correct defaults when env vars are absent (`PORT` defaults to `3000`, `PDS_URL` defaults to `https://bsky.social`)
7171+- Parses `PORT` as an integer (not a string)
7272+- Returns provided env var values when set
7373+- Handles `PORT` set to a non-numeric string (currently `parseInt` would return `NaN` — should this throw?)
7474+7575+**Why it matters:** Config loading is the root of most "it works on my machine" bugs. The current implementation silently accepts empty strings for `forumDid` and `databaseUrl`, which will cause hard-to-debug runtime failures. Tests would document this behavior and motivate adding validation.
7676+7777+#### c) Database schema tests (medium value)
7878+7979+**File:** `src/db/schema.ts`
8080+8181+**What to test:**
8282+- Schema definitions export the expected table names
8383+- Column types match expectations (e.g., `posts.deleted` defaults to `false`)
8484+- Foreign key references are correct (`posts.did` → `users.did`, `posts.rootPostId` → `posts.id`, etc.)
8585+- Index names are correct and unique constraints are in place
8686+8787+**How:** These can be pure unit tests against the Drizzle schema objects — no database connection needed. Drizzle table objects expose `._.columns` and other metadata you can assert against.
8888+8989+**Why it matters:** Schema is the foundation. If someone accidentally removes an index or changes a foreign key, these tests catch it before it hits a migration.
9090+9191+#### d) Database integration tests (high value, but requires infrastructure)
9292+9393+**What to test:**
9494+- Insert/select/update/delete for each table
9595+- Foreign key constraints are enforced (e.g., inserting a post with a non-existent `did` fails)
9696+- Unique index violations behave as expected
9797+- The `createDb()` factory produces a working Drizzle client
9898+9999+**How:** Use a test PostgreSQL instance. Options:
100100+- **Testcontainers** (Docker-based, spins up a real Postgres per test suite)
101101+- **pg-mem** (in-memory Postgres emulator, faster but not 100% compatible)
102102+- A shared test database with transaction rollback between tests
103103+104104+**Why it matters:** This is where the most subtle bugs live — constraint violations, bad joins, missing indexes. As the appview stubs are fleshed out with real queries, these tests become critical.
105105+106106+#### e) AT Protocol agent factory test (low value now, higher later)
107107+108108+**File:** `src/lib/atproto.ts`
109109+110110+Currently just `new AtpAgent({ service: config.pdsUrl })` — not much to test. But as authentication and record-writing logic is added, this module should have tests verifying:
111111+- Agent is created with the correct service URL
112112+- Authentication errors are handled gracefully
113113+- Record write/read operations produce expected AT URI formats
114114+115115+---
116116+117117+### 2. `@atbb/web` — Server-Rendered Web UI
118118+119119+#### a) API client tests (high value)
120120+121121+**File:** `src/lib/api.ts`
122122+123123+**What to test:**
124124+- `fetchApi("/categories")` calls the correct URL (`${appviewUrl}/api/categories`)
125125+- Throws an `Error` with status code and status text on non-2xx responses
126126+- Returns parsed JSON on success
127127+- Handles network failures (fetch throws)
128128+129129+**How:** Mock `global.fetch` with `vi.fn()` or use `msw` (Mock Service Worker):
130130+```ts
131131+import { describe, it, expect, vi, beforeEach } from "vitest";
132132+133133+// Mock fetch globally
134134+const mockFetch = vi.fn();
135135+vi.stubGlobal("fetch", mockFetch);
136136+137137+describe("fetchApi", () => {
138138+ it("throws on non-ok response", async () => {
139139+ mockFetch.mockResolvedValueOnce({
140140+ ok: false, status: 500, statusText: "Internal Server Error",
141141+ });
142142+ const { fetchApi } = await import("../src/lib/api.js");
143143+ await expect(fetchApi("/test")).rejects.toThrow("AppView API error: 500");
144144+ });
145145+});
146146+```
147147+148148+**Why it matters:** `fetchApi` is the single point of contact between the web UI and the appview. Error handling here determines whether users see useful error messages or blank pages.
149149+150150+#### b) JSX component / layout tests (medium value)
151151+152152+**File:** `src/layouts/base.tsx`, `src/routes/home.tsx`
153153+154154+**What to test:**
155155+- `BaseLayout` renders valid HTML with the provided title
156156+- `BaseLayout` uses the default title "atBB Forum" when none is provided
157157+- `BaseLayout` includes the HTMX script tag
158158+- Home route returns `200` with `text/html` content type
159159+- Home page includes "Welcome to atBB" heading
160160+161161+**How:** Use Hono's `app.request()` and assert against the HTML string, or use a lightweight HTML parser. Hono JSX components can be tested by rendering them and checking the output string.
162162+163163+#### c) Config loading tests (low-medium value)
164164+165165+**File:** `src/lib/config.ts`
166166+167167+Same pattern as the appview config tests — verify defaults, parsing, and presence of required values.
168168+169169+---
170170+171171+### 3. `@atbb/lexicon` — Lexicon Definitions
172172+173173+#### a) YAML-to-JSON build script tests (medium value)
174174+175175+**File:** `scripts/build.ts`
176176+177177+**What to test:**
178178+- Each YAML file in `lexicons/` produces valid JSON
179179+- Output JSON matches the expected Lexicon schema structure (has `lexicon`, `id`, `defs` fields)
180180+- No duplicate lexicon IDs across files
181181+- The `id` field in each lexicon matches its file path (e.g., `space/atbb/post.yaml` has `id: "space.atbb.post"`)
182182+183183+**How:** Rather than testing the build script directly (it's I/O-heavy), write validation tests that run against the YAML source files:
184184+```ts
185185+import { parse } from "yaml";
186186+import { readFileSync } from "fs";
187187+import { glob } from "glob";
188188+189189+describe("lexicon definitions", () => {
190190+ const files = glob.sync("**/*.yaml", { cwd: "lexicons" });
191191+192192+ it.each(files)("%s has a valid lexicon structure", (file) => {
193193+ const content = readFileSync(`lexicons/${file}`, "utf-8");
194194+ const parsed = parse(content);
195195+ expect(parsed).toHaveProperty("lexicon", 1);
196196+ expect(parsed).toHaveProperty("id");
197197+ expect(parsed).toHaveProperty("defs");
198198+ });
199199+});
200200+```
201201+202202+**Why it matters:** Lexicon definitions are the API contract for the entire AT Protocol integration. A malformed lexicon causes downstream build failures in type generation and runtime validation errors. Catching issues at the YAML level is far cheaper than debugging them at the API level.
203203+204204+#### b) Schema contract tests (high value)
205205+206206+**What to test:**
207207+- `space.atbb.post` has `text` as a required string field
208208+- `space.atbb.post` has optional `reply` with `root` and `parent` refs
209209+- `space.atbb.forum.forum` uses `key: literal:self`
210210+- `space.atbb.forum.category` uses `key: tid`
211211+- All `strongRef` usages have both `uri` and `cid` fields
212212+- `knownValues` are used (not `enum`) for extensible fields like `modAction.action`
213213+214214+**Why it matters:** These are the **contract tests** of the system. If a lexicon field is accidentally renamed or a required field becomes optional, it breaks interoperability with any PDS that stores atBB records. These tests protect the public API surface.
215215+216216+---
217217+218218+### 4. `@atbb/spike` — PDS Integration Script
219219+220220+The spike is a manual integration test. It doesn't need unit tests itself, but:
221221+222222+#### Extractable test utilities (medium value)
223223+224224+The spike contains reusable patterns for:
225225+- Authenticating with a PDS
226226+- Creating/reading/deleting AT Protocol records
227227+- Generating TIDs
228228+229229+These should be extracted into a shared test utility module (e.g., `packages/test-utils/`) that integration tests across the monorepo can use.
230230+231231+---
232232+233233+## Priority Matrix
234234+235235+| Priority | Area | Package | Effort | Impact |
236236+|----------|------|---------|--------|--------|
237237+| **P0** | Test infrastructure setup (vitest, turbo task, CI) | root | Low | Unblocks everything |
238238+| **P0** | Appview route handler tests | appview | Low | Catches regressions as stubs are implemented |
239239+| **P1** | Web API client tests (`fetchApi`) | web | Low | Validates the only web→appview boundary |
240240+| **P1** | Lexicon schema contract tests | lexicon | Low | Protects the AT Protocol API surface |
241241+| **P1** | Config loading tests (both packages) | appview, web | Low | Documents defaults, catches parse bugs |
242242+| **P2** | Database schema unit tests | appview | Medium | Catches accidental schema changes |
243243+| **P2** | JSX layout/component tests | web | Medium | Ensures correct HTML output |
244244+| **P2** | Lexicon build script validation | lexicon | Low | Catches YAML/JSON conversion issues |
245245+| **P3** | Database integration tests | appview | High | Requires Postgres test infra (Docker/testcontainers) |
246246+| **P3** | AT Protocol integration tests | appview | High | Requires PDS test instance or mock |
247247+| **P3** | Extract spike utilities into shared test-utils | spike | Medium | Enables reuse across integration tests |
248248+249249+---
250250+251251+## Suggested Implementation Order
252252+253253+1. **Set up vitest** at the root + per-package, add `test` task to turbo.json
254254+2. **Appview route tests** — quick wins since Hono has a built-in test helper and the routes are simple right now
255255+3. **Lexicon contract tests** — validate YAML schema structure to protect the AT Protocol API
256256+4. **Web `fetchApi` tests** — mock fetch, verify URL construction and error handling
257257+5. **Config tests** for both packages — small but catches real bugs
258258+6. **Database schema tests** — assert on Drizzle metadata objects
259259+7. **Database integration tests** — add testcontainers or similar once there are real queries to test
+4-2
package.json
···66 "build": "turbo run build",
77 "dev": "turbo run dev",
88 "lint": "turbo run lint",
99- "clean": "turbo run clean"
99+ "clean": "turbo run clean",
1010+ "test": "turbo run test"
1011 },
1112 "devDependencies": {
1213 "turbo": "^2.4.0",
1313- "typescript": "^5.7.0"
1414+ "typescript": "^5.7.0",
1515+ "vitest": "^4.0.18"
1416 }
1517}