Skip to content

chore(types): typecheck the test suite, starting with the unit lane - #607

Merged
Ardnived merged 6 commits into
mainfrom
chore/typecheck-test-suite-unit-lane
Jul 31, 2026
Merged

Ardnived merged 6 commits into
mainfrom
chore/typecheck-test-suite-unit-lane

Conversation

@Ardnived

Copy link
Copy Markdown
Contributor

Summary

  • No file under tests/ was ever typechecked — tsconfig.json excludes tests, ESLint doesn't typecheck, and Vitest's esbuild erases types without checking them. Adds a gate that does.
  • Clears the 34 errors that gate surfaced, including two imports of types that don't exist and five stale role slugs.
  • Scoped to the unit lane; widening to tests/int/** (~154 errors) is Phase 2, deliberately not in this PR.

Changes

  • tsconfig.test.json (new) — extends the root config, includes tests/unit/** + tests/utils/**. tsconfig.json is untouched, so this carries zero risk of changing what the Next.js build ships.
  • package.json — adds typecheck:tests. typecheck stays src-only rather than composing both, so a failure names the lane it came from.
  • .claude/skills/pr-prep/check.sh, .github/workflows/ci.yml — run it as its own Tier 2 / Tier 3 step.
  • tests/utils/testData.ts — the three concentrated root causes in the shared factory (below).
  • tests/unit/** (9 files) — each spec now types its fixtures against the real contract instead of a hand-written approximation.
  • .claude/rules/testing-reqs.md, AGENTS.md, .claude/docs/workflow-parity.md — tier tables documented Tier 2/3 as lint && typecheck && test.

What the exclusion was hiding

  • Imports of types that don't exist. ManagerRole / ClientRole were imported from @/payload-types, which exports neither — the suite passed only because esbuild strips type imports without resolving them. @/payload-types exports just the combined RoleSlug, so the two subsets are now derived from each collection's own roles field and track it automatically.
  • Five stale role slugs. dummyUser took Partial<Manager | Client>, checking roles against the generated flat array — which both admits invalid slugs and rejects the localized per-locale form the spec actually uses. Retyping it surfaced 'translator' (×5, now 'web-translator') and 'wemeditate-web' (now 'wemeditate-web-client'; the -client suffix exists precisely to disambiguate roles from project slugs). Outcomes are unchanged — clients skip locale filtering entirely, and the manager cases only need a non-empty array per locale — so all 12 cases still pass, now for the right reason.
  • A spread that could clobber the collection discriminator. { collection: 'managers', ...manager } put the spread last, with an as cast hiding it, against a rule (.claude/rules/tests.md) that access-control mocks must carry it. No runtime misbehaviour today — Payload's returned doc has no collection key, so there was nothing to overwrite, and the 54 access specs pass either way — but it was one generated-type change away from breaking silently. Corrected; the cast is no longer needed.

Test Results

  • pnpm typecheck:tests: ✓ exits 0 (from 34 errors / 10 files)
  • Unit: ✓ 849 passed (81 files)
  • Integration (targeted): ✓ role-based-access 54, app-cards-for-audience 32, collections-smoke 19 — the specs covering the factory changes that aren't purely type-level
  • Lint: ✓ no errors · pnpm typecheck (src): ✓ unchanged
  • Tier 2 lean gate: ✓ 19–20 s, against its < 45 s target (the new step adds ~4 s)

Mutation-checked, so the gate isn't passing vacuously. Injecting level: 'venue' into a factory — the exact shape of the #605 escape — fails with Type '"venue"' is not assignable to type '"region" | "center" | "country" | "city"'. Review separately confirmed that createData's Partial still rejects an unknown property (nmae) and that dummyUser still rejects an invalid role slug.

Notes for reviewer

  • createData is the one deliberate loosening. Payload derives create's data type from the generated output doc, so any field it fills in itself (slug via slugField, userChoices.type, appCards.default.aspectRatio) is demanded on input, and the Partial<Doc> overrides these factories spread in re-widen required keys to T | undefined. Modelling the payload as partial trades "you forgot a required field" — which Payload validates at runtime, and the int lane exercises — for "every field you do pass is real and correctly typed", which is the rot chore(types): typecheck the test suite, starting with the unit lane #606 is about. Excess-property checking survives, verified above.
  • createAppCard now passes aspectRatio: 'square' / alignment: 'center' explicitly: default is a nested group, so the top-level Partial doesn't reach inside it, and both are required: true with a defaultValue. Values match the collection's declared defaults, so runtime is identical.
  • Two src-level follow-ups I left out to keep this scoped to tests, both worth doing in Phase 2: TypedAuthUser['roles']'s localized form is typed Record<LocaleCode, RoleSlug[]> but is genuinely partial (both readers already do roles[locale] || [] / ?.length > 0); and urlField declares its return as TextField while pinning hasMany: false and internally casting validate to TextFieldSingleValidation, so callers must repeat that cast. I started the first, then reverted it — a shipping-code type change didn't belong in a test-typing PR.
  • The pre-existing tests/tsconfig.json is editor-only (no script or CI step references it) and covers all of tests/**. Left alone for a minimal diff; Phase 2 should collapse the two.
  • workflow-parity.md's lean-gate cell for this repo was already stale (it omitted typecheck entirely) — corrected here, so /sync-workflow should propagate it to SahajAtlasWeb and WeMeditateWeb.

Refs #606 — Phase 1 only; Phase 2 (tests/int/**) remains open.

🤖 Generated with Claude Code

Ardnived and others added 6 commits July 30, 2026 20:13
`tsconfig.json` excludes `tests`, and it's the config the Next.js build
consumes — so the test lane gets its own `tsconfig.test.json` instead,
keeping this work off the shipping build. Scoped to the unit lane for now.

`typecheck` stays src-only rather than composing both, so a failure names
the lane it came from.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three kinds of rot the `tests` exclusion was hiding in the factory every
other spec depends on:

- `ManagerRole` / `ClientRole` were imported from `@/payload-types`, which
  exports neither — the suite only passed because esbuild strips type
  imports without resolving them. `@/payload-types` exports just the
  combined `RoleSlug`, so derive the two subsets from each collection's own
  `roles` field instead; they now track it automatically.
- `{ collection: 'managers', ...manager }` put the spread last, where it can
  clobber the discriminator that `.claude/rules/tests.md` requires on
  access-control mocks — with an `as` cast hiding it. No runtime misbehaviour
  today (Payload's returned doc carries no `collection` key, so there was
  nothing to overwrite), but the ordering was one generated-type change away
  from breaking silently. Corrected, and the cast is no longer needed.
- Factories spread `Partial<Doc>` overrides into `payload.create`'s `data`,
  which Payload types from the *output* doc — so every field with a
  `defaultValue` or a filling hook is demanded on input. Route those payloads
  through a `createData` seam that keeps each passed field checked (real field,
  valid type) and lets Payload supply the rest.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`dummyUser` took `Partial<Manager | Client>`, so `roles` was checked against
the generated flat array — which both admits invalid slugs in the localized
form the spec actually uses, and rejects that form outright. Give it a
`DummyUserOverrides` type that keeps the doc fields but declares `roles` as
"flat array or per-locale record", matching what the code reads at runtime.

That surfaced two stale literals, neither a valid role slug:

- `'translator'` (×5) → `'web-translator'`, the current slug
- `'wemeditate-web'` → `'wemeditate-web-client'`; the `-client` suffix exists
  precisely to disambiguate roles from project slugs (`.claude/rules/access.md`)

Outcomes are unchanged — client requests skip locale filtering entirely, and
the manager cases only need a non-empty array per locale — so all 12 cases
still pass, now for the right reason.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Each spec now types its fixtures against the real contract instead of a
hand-written approximation:

- document-managers: `'things'` isn't a collection, so `ContentSlug` rejected
  it. The slug is incidental to what these cases assert (polymorphic matching,
  cycle termination), so use the real ones the shapes belong to — `events` and
  `regions`. `selfParent`/`payloadWithFields` take `CollectionSlug`.
- lectures-for-audience-helpers: override rows were `{ locale: string }`, which
  a hand-written cast then re-asserted. Type them as `Lecture['subtitles']`, so
  locale codes are checked against the real union.
- thumbnail-url: the mock was cast to `{ id, url }`, which isn't a
  `ThumbnailRef`; cast to `Image`, the relationship it stands in for.
- url-field: `urlField` returns `TextField`, whose `validate` widens to the
  hasMany union, so a `string` argument didn't fit. Narrow to the
  `TextFieldSingleValidation` the factory itself casts to.
- server-env: `NODE_ENV` is required on `ProcessEnv`; carry it through the
  cleared-env cases, none of which are testing that variable.
- registration-details / openapi-endpoint-auth: widen `title` to allow the
  `null` whose fallback is under test, and cast the minimal plugin config
  through `unknown`.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Adds `pnpm typecheck:tests` to the pr-prep lean gate and the CI job, as its
own step so a failure names the lane it came from. Tier 2 measures 20s,
inside its 45s target.

Docs synced: the tier tables in `.claude/rules/testing-reqs.md` and
`AGENTS.md` both documented Tier 2/3 as `lint && typecheck && test`, plus a
note on why the two typecheck passes are separate. The `workflow-parity.md`
lean-gate cell for this repo was already stale (it omitted `typecheck`) —
corrected, so `/sync-workflow` should propagate it to the sibling repos.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
18 lines for a one-line cast; same substance in 12.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app

railway-app Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-607 environment in sahajcloud

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Jul 31, 2026 at 3:45 am

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-607 July 31, 2026 03:43 Destroyed
@Ardnived
Ardnived merged commit 3be34cc into main Jul 31, 2026
2 checks passed
Ardnived added a commit that referenced this pull request Aug 4, 2026
* chore(types): widen the test typecheck gate to the whole suite

Phase 1 (#607) scoped `tsconfig.test.json` to `tests/unit/**` +
`tests/utils/**`. Widen `include` to `tests/**` and collapse the
editor-only `tests/tsconfig.json` into a one-line re-export, so the
editor and `pnpm typecheck:tests` read one set of options.

Both configs resolve the same 153 files. Dropping the local
`types: ["vitest/globals"]` is safe — every Vitest spec imports its
globals explicitly, and the e2e specs take theirs from
`@playwright/test`.

This commit turns the gate red (158 errors / 26 files, all
`tests/int/**`); the rest of the branch clears them.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(jobs): share one typed task-handler runner across the job specs

Five int specs hand-rolled the same "call a task handler without the
queue" block and typed its args with
`Parameters<typeof SomeTask.handler>[0]`. That never compiled:
`TaskConfig['handler']` is `string | TaskHandler<TSlug>` (a task may
point at a module path), and `Parameters<T>` rejects the union — 20 of
#606 Phase 2's errors, plus the 11 downstream casts they forced.

`tests/utils/taskRunner.ts` narrows the union with a `typeof` guard, so
`TaskHandlerArgs<TSlug>` is available for the queue-plumbing stubs and
no cast is needed. Its return type comes from the generated `TypedJobs`
output schema, which retires five hand-maintained duplicates of the job
output shapes (`ExpireResult`, `DigestResult`, `SyncOutput`, …) — those
are now checked against the job's real contract instead of drifting
from it.

`inlineTask` throws instead of no-op'ing: no task under test uses
sub-tasks, and returning `undefined` where an output is expected is the
kind of lie the old cast was hiding.

158 -> 127 errors. expire-events + sync-lecture-metadata pass locally.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(fixtures): make fixture overrides optional at every depth

Two shared type faults, ~50 of #606 Phase 2's errors between them.

`Partial<Doc>` on the factory `overrides` params relaxes only the top
level, so passing a group or an array row obliged the test to supply
that subtree's required keys in full — `default: { title, image }` on
an app card was rejected for omitting aspectRatio/textColor/alignment,
which AppCards fills from `defaultValue` anyway. `FixtureOverrides<T>`
recurses, and the checks worth keeping stay: an unknown property, or a
real property at the wrong type, still errors at any depth, and unions
distribute so relationships keep taking a bare id.

Ten factories passed `data:` straight to `payload.create` rather than
through `createData`, so deep-partial values had nowhere to widen.
Routed through the same seam as the other nine.

`CapturedLogger` typed each method `ReturnType<typeof vi.fn>`, which
resolves the generic to its *constraint* (`Mock<Procedure |
Constructable>`) instead of its default — so the mock wasn't callable
as `(obj: object) => void` and every `handleStreamWebhook({ logger })`
call failed. Mapping over `WebhookLogger` fixes it and makes a new
method on the interface break `makeLogger` instead of going unmocked.

Both are type-only: no runtime behaviour changes. 127 -> 95 errors,
`tests/utils/` back to clean.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(access): type the role-based-access fixtures against the real schema

Clears role-based-access.int.spec.ts (26 errors, the worst file) plus
the shared causes behind it.

`RegionFixture` was `Record<string, unknown> & { level?: RegionLevel }`.
Its doc comment noted the narrowing was inert because tsc never read
the file — Phase 2 makes it live, so it's now `FixtureOverrides<Region>`
and checks the whole fixture, not just `level`. `createEvent`'s
`Record<string, unknown>` gets the same treatment, and `managerUser` /
`createRegion` take the real manager-fixture type instead of
`{ id: number }` (which dropped every other field and so wasn't a
`Manager`).

`FixtureOverrides` and `createData` are now exported: specs building
inline `payload.create` helpers need the same seam. Without `createData`
here, an omitted `slug` pushes TS onto the *draft* create overload and
it reports "Property 'draft' is missing" — 8 errors that read as
nothing to do with the actual cause.

`createTestLexicalContent` gets a return-type annotation; inferred, its
`direction`/`format` widen to `string` and no `richText` field accepts
the result (7 errors).

`select: { id: true }` (11 sites) doesn't typecheck because Payload
omits `id` from the generated `…Select` types — it's always returned.
Replaced with an `idOnlySelect()` helper carrying one documented
assertion. Note `select: {}` is NOT equivalent: `validateClientQuery`
rejects an empty select with a 400, which the first attempt at this hit
(7 failures). Verified by running the spec, not by reading the types.

158 -> 68 errors. role-based-access + pages: 73 tests pass.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* chore(lint): fix import order in role-based-access spec

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(lectures): drop the blanket `as any` on lecture create fixtures

Eight `payload.create({...} as any)` calls cast away the argument type,
which also collapsed the *return* type to a union over every collection
— so `lecture.title` / `.metadata` / `.thumbnail` didn't exist on it
(7 errors that read like missing fields but were self-inflicted). The
cast was there to dodge the create-data type; `createData<'lectures'>`
handles that properly and keeps the result a Lecture.

The eight `fetchNirmalaVidyaVideo` mocks were also each missing
`duration`, required on `NirmalaVidyaVideoData` and read by
`populateFromNirmalaVidya` — the mocks were passing `undefined` where
the contract says `number | null`. Real rot the exclusion was hiding.

68 -> 53 errors. 32 tests pass.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(int): route inline create fixtures through createData; drop dead keys

The bulk of the remaining tail was one shape: a spec building its own
`payload.create` call with a plain object literal. Because Payload
derives the create-data type from the *output* doc, an omitted
auto-filled field (`slug`) makes TS pick the draft overload and
complain about `draft`. `createData<'slug'>` is the seam for that;
applied to the region, event and audience fixtures across 10 specs.

Two pieces of real rot fall out:

- `rules: { logic: 'AND', pathProgress: … }` on 7 audience fixtures.
  Audiences has no `rules` field — it was flattened into top-level
  range groups — so Payload has been silently dropping it. Removed
  rather than translated: `/lectures/for-audience` matches on audience
  *id* overlap, never on rule evaluation, so no test reads it.
- The five `SCHEDULE` fixtures pinned `recurrenceType` with `as const`
  but left `firstDate_tz` widening to `string`, so none of them
  satisfied `SupportedTimezones`. Whole object is `as const` now.

68 -> 22 errors.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(int): clear the last 22 typecheck errors in the int lane

Per-spec tail. Several were real defects the exclusion had been hiding:

- api: `createMeditation(payload, { title })` put the title in the
  factory's `deps` slot (2nd param) instead of `overrides` (3rd), so
  the meditation got a random label; and `populate` was keyed on the
  field name rather than the target collection, making it a no-op.
- audiences: `createAppCard(payload, { title })` — AppCard's title
  lives under the `default` group, so it was silently dropped.
- app-cards-for-audience: `toHaveLength(1, 'message')` — the matcher
  takes one argument and the message was discarded.
- wemeditateAppStatus: the invariant fixture omitted `label` and
  `description`, both required on SectionSpec.

The rest are honest typing: `LIST_VIEW_SELECT` annotated so `true`
stops widening to `boolean` (and the column names get checked),
`common` in events-geojson annotated rather than `as const` (which
froze `languages` to a readonly tuple), `Event`/`Video`/`Region`
imported where the DOM globals were resolving instead, and a documented
`schedule: null` sentinel type in event-verification's fixture helper.

Casts kept only where a test is deliberately out-of-contract — videos'
malformed subtitle row, meditations' `locale: 'all'` (real Payload
value, absent from the generated union), and events' `_status`
assertion (left out of the select on purpose, to prove the plugin
injects it).

`pnpm typecheck:tests` now exits 0 over the whole suite. Full lane
verified green: 54 int files / 885 tests, 85 unit files / 978 tests.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(tests): document the widened gate and the typed-fixture helpers

The tier tables in AGENTS.md and testing-reqs.md described
`typecheck:tests` as unit-lane-only; it now covers `tests/**`.

Adds a "Typed fixtures" section to `.claude/rules/tests.md` (the rule
that auto-loads when editing a spec) covering `createData` /
`FixtureOverrides` — including *why* each exists, since both failure
modes are non-obvious: an omitted auto-filled field makes tsc report
"Property 'draft' is missing", and `Partial<Doc>` silently stops
relaxing one level down. Also notes `runTaskHandler`, and that
`idOnlySelect()` is not interchangeable with `select: {}`.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(tests): drop the unreachable Date branch from FixtureOverrides

Per /simplify. Payload generates every date field as an ISO `string`
(`grep -cE ':\s*Date\b' src/payload-types.ts` -> 0), so the branch could
never be taken. Noted the assumption in the doc comment instead.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(pr-prep): correct the gate's scope message after the widening

check.sh still told the reader the test typecheck was "scoped to the
unit lane" and named `tests/unit + tests/utils` in its failure hint.
Points at the fixture helpers on failure, which is what a spec author
who trips it needs next.

Refs #606

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-607 — b9e9e074 Deployed Jul 31, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant