Repository navigation
chore(types): typecheck the test suite, starting with the unit lane - #607
Merged
Merged
Conversation
`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]>
|
🚅 Deployed to the SahajCloud-pr-607 environment in sahajcloud
|
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-607
July 31, 2026 03:43
Destroyed
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
tests/was ever typechecked —tsconfig.jsonexcludestests, ESLint doesn't typecheck, and Vitest's esbuild erases types without checking them. Adds a gate that does.tests/int/**(~154 errors) is Phase 2, deliberately not in this PR.Changes
tsconfig.test.json(new) — extends the root config, includestests/unit/**+tests/utils/**.tsconfig.jsonis untouched, so this carries zero risk of changing what the Next.js build ships.package.json— addstypecheck:tests.typecheckstays 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 aslint && typecheck && test.What the exclusion was hiding
ManagerRole/ClientRolewere imported from@/payload-types, which exports neither — the suite passed only because esbuild strips type imports without resolving them.@/payload-typesexports just the combinedRoleSlug, so the two subsets are now derived from each collection's ownrolesfield and track it automatically.dummyUsertookPartial<Manager | Client>, checkingrolesagainst 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-clientsuffix 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.collectiondiscriminator.{ collection: 'managers', ...manager }put the spread last, with anascast 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 nocollectionkey, 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)role-based-access54,app-cards-for-audience32,collections-smoke19 — the specs covering the factory changes that aren't purely type-levelpnpm typecheck(src): ✓ unchangedMutation-checked, so the gate isn't passing vacuously. Injecting
level: 'venue'into a factory — the exact shape of the #605 escape — fails withType '"venue"' is not assignable to type '"region" | "center" | "country" | "city"'. Review separately confirmed thatcreateData'sPartialstill rejects an unknown property (nmae) and thatdummyUserstill rejects an invalid role slug.Notes for reviewer
createDatais the one deliberate loosening. Payload derivescreate'sdatatype from the generated output doc, so any field it fills in itself (slugviaslugField,userChoices.type,appCards.default.aspectRatio) is demanded on input, and thePartial<Doc>overrides these factories spread in re-widen required keys toT | 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.createAppCardnow passesaspectRatio: 'square'/alignment: 'center'explicitly:defaultis a nested group, so the top-levelPartialdoesn't reach inside it, and both arerequired: truewith adefaultValue. Values match the collection's declared defaults, so runtime is identical.TypedAuthUser['roles']'s localized form is typedRecord<LocaleCode, RoleSlug[]>but is genuinely partial (both readers already doroles[locale] || []/?.length > 0); andurlFielddeclares its return asTextFieldwhile pinninghasMany: falseand internally castingvalidatetoTextFieldSingleValidation, 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.tests/tsconfig.jsonis editor-only (no script or CI step references it) and covers all oftests/**. 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 omittedtypecheckentirely) — corrected here, so/sync-workflowshould propagate it to SahajAtlasWeb and WeMeditateWeb.Refs #606 — Phase 1 only; Phase 2 (
tests/int/**) remains open.🤖 Generated with Claude Code