Frontend Vitest Test Expansion Plan¶
Status: Partly implemented test strategy and historical rollout record. Phase 1 is complete; remaining priorities must be reconciled with the current suite before implementation.
Audience: Frontend engineers and reviewers planning unit or component coverage.
Task¶
Expand the existing frontend Vitest suite with high-impact, deterministic unit and component tests.
This plan was intentionally limited to Vitest and did not add browser tests. Focused Playwright smoke journeys are now maintained separately; they do not replace this suite. Do not rewrite production components merely to make them testable unless extracting a small pure helper materially simplifies important behavior.
Goals¶
Prioritize regressions involving:
- Buttons enabled or disabled in the correct state
- Privileged or feature-flagged UI shown only to eligible users
- Pending operations preventing duplicate submission
- Correct success and error messages
- Daily-date and Pacific-time behavior
- Singular/plural and quantity-sensitive copy
- Completed versus active gameplay behavior
- Scroll-position management
- Truncation and overflow contracts
- Destructive actions requiring explicit confirmation
- Analytics and consent behavior
- Navigation behavior based on game context
Prefer behavioral assertions using roles, labels, accessible names, and visible text. Avoid broad snapshots and tests that merely duplicate component implementation.
Current Test Setup¶
The original configuration was intentionally Node-only. As of 2026-08-23, Phase 1 has shipped:
frontend/minigames/vitest.config.tskeeps Node as the default environment.- The include pattern covers both
src/**/*.test.tsandsrc/**/*.test.tsx. - Component tests opt into jsdom per file and use Testing Library.
- The suite currently passes 421 tests across 46 files on
bug/adsense-review-2. - Coverage now includes the original pure helpers plus gameplay state, time calculations, feature flags, consent, advertising eligibility/previews, forms, standings, navigation, public metadata, crawler files, legal-page discovery, game-shaped loading states, and full-document load recovery.
The AdSense review follow-up added focused checks in:
src/app/adsense-verification.test.tssrc/app/crawl-metadata.test.tssrc/app/site-metadata.test.tssrc/app/components/game-card.test.tsxsrc/app/components/puzzle-loading.test.tsxsrc/app/components/game-load-error.test.tsxsrc/app/components/game-load-retry.test.tssrc/app/games/game-loading-routes.test.tsxsrc/app/terms/page.test.tsx
These tests intentionally stop at deterministic component and contract behavior. Pixel geometry, actual browser navigation, provider crawler timing, and the external AdSense dashboard still require manual or browser-level verification.
Preserve those tests and the fast Node environment for pure functions.
Phase 1: Add React Component Test Support¶
Add development dependencies:
jsdom@testing-library/react@testing-library/jest-dom@testing-library/user-event
Update Vitest to include both:
src/**/*.test.tssrc/**/*.test.tsx
Keep environment: "node" as the default. Put this directive at the top of component test files:
Add a small test setup file that:
- Imports
@testing-library/jest-dom/vitest - Runs Testing Library cleanup after each test
- Restores mocks and fake timers
- Adds browser API shims only when genuinely required
Do not install or add a React/Vite plugin unless the tests demonstrate that TSX transformation requires it. Vitest/esbuild should already handle TSX.
Useful test utilities:
- A deferred-promise helper for testing pending UI
- A lightweight
next/navigationrouter mock - A simple
next/linkmock only where Next's real Link causes unnecessary noise - A
renderWithGameStorehelper that accepts a real Letter Golf Zustand store - A configurable
matchMediamock - Factories for Puzzle, Player, Group, and Standings response objects
Avoid large global mocks. Keep mocks local to the owning test whenever practical.
Phase 2: Highest-Value Pure Logic Tests¶
These should remain Node-environment .test.ts tests.
2.1 Letter Golf Game Store¶
Create:
src/app/games/letter-golf/store/game.test.ts
This is the highest-priority addition because it controls word acceptance and gameplay state.
Test:
initializeuppercases target keys and stores wildcard count.initializechangesloadingto false.setCurrentWordtrims and lowercases input.updateCurrentWordapplies the update and normalizes the result.restoreWordsnormalizes words to uppercase and removes duplicates.removeWordremoves the normalized word without mutating the previous Set.getLetterCountscorrectly counts repeated letters across words.getTargetCountsconsumes target letters before wildcards.- Letters absent from the target consume wildcards.
- Excess letters make the wildcard remainder negative.
getTargetCountsdoes not mutate either input object.- A word shorter than three characters returns
TooShort, clears current input, and never callsverifyWord. - Invalid characters return
InvalidCharacterswithout calling the backend. - A repeated word returns
Repeatedwithout calling the backend. - Excess wildcard use returns
TooManyWildcardswithout calling the backend. - A dictionary rejection returns
NotAWord, clears input, and does not add the word. - A successful verification adds the uppercase word and clears input.
- A verification exception returns
NetworkError, clears input, and preserves existing words. - A submit in progress cannot accidentally be represented as success before verification resolves, if that behavior exists in the store.
Before asserting that initialize clears or preserves existing words, inspect its callers and confirm the intended puzzle-transition contract. Do not freeze ambiguous behavior in a test without resolving it.
2.2 Streak and Pacific-Date Behavior¶
Create:
src/lib/streak.test.ts
Use vi.useFakeTimers() and vi.setSystemTime() where appropriate.
Test:
formatDayCount(0)produces0 days.formatDayCount(1)produces1 day.formatDayCount(2)produces2 days.- Pacific date immediately before winter midnight is the previous calendar day.
- Pacific date immediately after winter midnight is the new calendar day.
- Repeat the boundary around summer/PDT midnight.
- Playing today returns
Daily complete!. - Playing yesterday returns the streak-preservation prompt.
- An older nonzero streak returns
Previous streak: N days. - An old or empty zero streak returns an empty status.
- Cover a DST-transition weekend to prevent local-machine timezone assumptions.
Use explicit UTC timestamps such as:
- Winter Pacific midnight boundary:
07:59:59Z/08:00:00Z - Summer Pacific midnight boundary:
06:59:59Z/07:00:00Z
2.3 Extract and Test the Daily Countdown¶
The Pacific-midnight countdown is currently nested inside the large Letter Golf game component.
Extract small pure helpers, for example:
Test:
- Midnight boundary
- One second before midnight
- Noon
- Leading-zero formatting
- Summer and winter Pacific offsets
- The
"24"hour value returned by someIntlimplementations at midnight - No dependence on the developer machine's local timezone
The component should continue owning the interval; only the calculation and formatting should move.
2.4 Date Formatting and Timer Formatting¶
Add tests for:
formatUpdateDateformatUpdateDateShortformatTime
Important cases:
- Update dates never shift backward for users west of UTC.
- Update dates never shift forward for users east of UTC.
formatTime: 0, 9, 59, 60, 61, and 3599 seconds.- Explicitly document whether durations over one hour remain total minutes or should become hours.
2.5 Feature Fetching¶
Create:
src/lib/features.test.ts
Test:
- Successful feature response is returned unchanged.
- Backend failure produces
{}rather than throwing. - An empty response is treated consistently.
- No feature defaults to enabled.
2.6 Consent and Analytics Helpers¶
Create:
src/app/analytics.test.ts
Use jsdom only if needed for window, localStorage, and CustomEvent.
Test:
- Stored
"true"maps togranted. - Stored
"false"maps todenied. - Missing or unrecognized storage maps to
null. - Granting consent writes
"true". - Denying consent writes
"false". gtag("consent", "update", ...)receives all four expected consent properties.- A
cookie-consent-changeevent is dispatched with the correct detail. - GA events include their supplied event name and metadata.
- Development logging and production
gtagbehavior do not throw when correctly configured.
Phase 3: High-Value Component Contracts¶
Use .test.tsx and jsdom.
3.1 Letter Golf Mode Switch¶
Create:
src/app/games/letter-golf/mode-switch.test.tsx
Test:
- Daily and Practice have
role="tab". - Current mode has
aria-selected="true"andtabIndex=0. - Inactive mode has
aria-selected="false"andtabIndex=-1. - Clicking Practice calls
onModeChange("practice"). - Clicking the already selected mode does not produce an unintended state.
- Disabled mode disables both tabs and prevents callbacks.
- ArrowRight and End select Practice.
- ArrowLeft and Home select Daily.
- Unsupported keys do nothing.
- Keyboard selection moves focus to the newly selected tab.
Use fake timers only for the deferred focus call.
3.2 Word List Active/Completed Behavior¶
Create:
src/app/games/letter-golf/wordlist.test.tsx
Render with a real test store.
Test:
- All played words render in uppercase.
- Active state shows one accessible Remove button per word.
- Clicking Remove deletes the correct word.
- Read-only/completed state has no Remove buttons.
- Active mode scrolls to the bottom when words change.
- Completed mode resets
scrollTopto zero. - Completed mode resets the stale scroll position synchronously after the state transition.
- Long words retain their full accessible text.
jsdom does not perform layout. Mock scrollHeight and spy on the scrollTop setter to validate the scroll-management behavior.
A narrow class-contract assertion is acceptable here:
- Active and read-only lists retain the intended overflow behavior.
- The inner list remains wrapping and center-justified.
Do not claim this proves that a real browser scrollbar is invisible.
3.3 Target Letters¶
Create:
src/app/games/letter-golf/targetletter.test.tsx
Test:
- Enabled target has
Add letter Xas its accessible name. - Clicking an enabled target appends the letter.
- Disabled/completed target has a remaining-count accessible name.
- Disabled target does not mutate the current word.
- Zero and negative counts display
0. - Positive count uses the active count treatment.
- A count change renders an animation strip.
- Firing
animationEndremoves the animation strip. - The safety timeout also removes a stale strip.
- Rerendering with the same count does not create a new animation.
- Reordering/remounting tiles does not resurrect an already-cleared animation.
The last cases protect the previously regressed shuffle/count-animation behavior.
3.4 Ad Eligibility and Reserved Space¶
Create:
src/app/components/ad-slot.test.tsxsrc/app/components/house-ad-preview.test.tsx
Test AdSlot:
- Without children, it reserves zero height.
- With content, it reserves the requested minimum height.
- Placement identity is emitted through
data-ad-placement. - Caller classes are preserved.
Test HouseAdPreview:
- Hidden while features are unresolved.
- Hidden when no flags are enabled.
- Shown at every implemented placement when only
AdPreviewEnabledis enabled. - Hidden when only the placement-specific flag is enabled.
- Shown when
AdPreviewEnabledand a placement flag are enabled whileAdsEnabledis off. - Hidden when
AdsEnabledand that placement flag select the location for live advertising. - Shown when a different placement is selected for live advertising.
- A feature-fetch failure leaves the slot collapsed.
- It uses the supplied placement and height.
- One live-placement flag cannot suppress a different placement's preview.
This provides direct coverage for “do or do not show UI to a particular user.”
3.5 Header-Menu Authorization¶
The full Radix menu is relatively expensive to test. Prefer first extracting a small pure helper that calculates which privileged tools are eligible from:
- Feature flags
- Presence of the current puzzle
- Presence of the actual Daily puzzle key
Test the matrix:
PuzzleMetadatarequires both its flag and a puzzle.DebugSolutionsrequires both its flag and a puzzle.ResetDailyrequires its flag and a Daily puzzle key.- Missing flags expose no privileged tools.
- A failed feature fetch exposes no privileged tools.
- No god-view separator is emitted when there are no god-view tools.
Add only one or two integration-level menu tests after the helper tests:
- An ordinary user never sees privileged items.
- A fully enabled test user sees the expected items.
Do not test Radix's internal generated markup.
3.6 Back-Link Behavior¶
Create:
src/app/components/back-link.test.tsx
Test:
- It always renders the fallback URL as a real link.
- With no useful browser history, clicking allows fallback navigation.
- With in-app history, clicking prevents link navigation and calls
router.back(). - The visible label and accessible name remain correct.
Do not use pixel assertions for arrow alignment.
3.7 Update and Long-Label Truncation Contracts¶
Create focused tests for:
UpdatesBanner- Victory group links
- Standings/member-name labels
Test:
- The full text remains in the DOM for accessibility.
- The element intended to shrink has
min-w-0. - The text element has the intended
truncateor line-clamp contract. - Long content does not get programmatically sliced into inaccessible text.
- A missing crumb does not render a stray slash.
These assertions protect the CSS contract. They do not prove that browser ellipsis occurred.
Phase 4: Forms and Destructive Workflows¶
4.1 Create Group Form¶
Create:
src/app/groups/create/create-group-form.test.tsx
Test:
- Submit is disabled for empty input.
- Submit is disabled for whitespace-only input.
- Valid input enables submission.
- A pending request changes the label to
Creating.... - A pending request disables duplicate submission.
- Success navigates to the returned group.
- HTTP 400 shows the validation/group-limit message.
- Other failures show the generic message.
- Failure restores the enabled state.
4.2 Join Group Form¶
Create:
src/app/groups/join/join-form.test.tsx
Test:
- Empty and whitespace-only codes disable submit.
- Codes are trimmed and uppercased before sending.
- A pending request displays
Joining...and prevents duplicates. - Success navigates to the returned group.
- 404, 409, 400, and generic errors show their respective messages.
- Invite-prefilled joins send
method: "invite_link"to analytics. - Manually typed joins send
method: "manual_code". - Changing a prefilled code does not incorrectly change its attribution method.
4.3 Settings¶
Create:
src/app/settings/settings-form.test.tsx
Prioritize:
- Initial display name and theme are rendered.
- Save becomes disabled and reads
Saving...while pending. - Successful save shows
Settings saved!. - Failed save shows
Failed to save settings. - Theme selection applies immediately and attempts persistence.
- Stored consent selects the correct privacy choice.
- Changing consent invokes the shared consent helper.
- Export becomes disabled while pending.
- Export produces a JSON Blob with the expected UTC-date filename.
- Object URLs are revoked after download.
- Delete confirmation opens with the destructive warning.
- Delete remains disabled for empty, lowercase, or partial confirmation.
- Delete enables only for exact
DELETE. - Successful delete navigates to
/?deleted=1. - Failed deletion does not navigate.
- Cancel does not delete anything.
The destructive-action tests are higher priority than testing every style or explanatory paragraph.
4.4 Cookie Banner¶
Create:
src/app/components/cookie-banner.test.tsx
Test:
- Nothing is shown before stored consent has been read.
- Existing granted consent suppresses the banner.
- Existing denied consent suppresses the banner.
- No stored choice displays the banner.
- “Accept only required cookies” stores denial and dismisses it.
- “Accept all cookies” stores consent and dismisses it.
- The privacy link points to
/privacy.
Phase 5: Social, Standings, and Victory UI¶
5.1 Event Standings Component¶
Create:
src/app/groups/[groupId]/event-standings.test.tsx
The underlying sorting already has unit coverage; focus on rendered decisions:
- Every current member appears.
- Completed players show scores.
- Playing users show
Playing. - Users without entries show
Not played. - The viewer is labelled
(you). - Viewer score and rank summary appears only after completion.
- A tied rank reads
Tied for 1st. - One member reads
1 member finished. - Multiple members read
N members finished. - Member links point to the group-scoped member URL.
- Long display names retain full text and the truncation contract.
5.2 Placeholder Nudge Behavior¶
Create a small test for NudgeMemberButton:
- It is disabled.
- It explains that nudging is not available.
- Clicking it performs no action.
This prevents placeholder UI from accidentally becoming an enabled dead control.
5.3 Victory Overlay¶
Create:
src/app/components/victory.test.tsx
Mock the confetti implementation.
Test:
- Invisible state is inaccessible or noninteractive according to the component's intended contract.
- Daily configuration shows sharing.
- Practice configuration can hide sharing.
- Practice primary and secondary actions invoke the correct callbacks.
- Close invokes
onClose. - Group links render only when
showGroupLinksis true and groups exist. - Each group link targets the correct group.
- Long group names retain full text and truncation classes.
- Successful native share emits GA only after the share promise resolves.
- Cancelled or rejected share emits no GA event.
- Successful clipboard copy includes the message and current URL.
- Failed clipboard copy emits no GA event.
- Confetti is delayed and cancelled if the component becomes invisible or unmounts first.
Optional Low-Cost Additions¶
Add these after the higher-impact batches.
Greeting¶
- Initial fallback reads
Verbolus. - Successful fetch shows
Welcome back, NAME!. - Failed fetch retains the fallback.
- Resolution after unmount does not update state.
Toast¶
- Uses
role="status"andaria-live="polite". - Auto-closes after the configured duration.
- Clicking Dismiss closes it.
- The timer is cleaned up on unmount.
useMediaQuery¶
- Reads the initial match.
- Responds to a media-query change event.
- Removes its listener on unmount.
Group Tabs¶
- Today is current on the group root route.
- Members is current on the members route.
- Neither route is incorrectly marked current on a member-detail page, unless product intent says otherwise.
Explicit Testing Boundaries¶
Scrollbars¶
jsdom does not calculate actual layout, scrollHeight, or scrollbar painting.
Vitest may validate:
scrollTopis reset or advanced correctly- Correct overflow classes are present
- Completed state removes controls that consumed space
- Word wrapping and centering classes remain attached
Vitest must not claim:
- “No scrollbar is visible at 412×915”
- “The list fits in exactly two rows”
Those require a real browser or manual responsive verification.
Truncation¶
Vitest may validate:
- Full accessible text remains present
- The shrinkable flex boundary has
min-w-0 - The intended text element has
truncateor line-clamp - No manual character slicing destroys the full label
Vitest cannot prove pixel-level ellipsis.
Hover and Alignment¶
Do not add brittle tests that merely inventory Tailwind classes across the entire application.
Only test a hover or focus class when it represents a specifically reported regression. Prefer accessibility and interaction assertions such as:
- The element is keyboard focusable
- An accessible name exists
- The focus-visible treatment contract is present
- Clicking invokes the correct behavior
Pixel alignment remains outside jsdom's capabilities.
Implementation Order and Commits¶
Use cohesive commits and do not squash them unless correcting a trivial mistake.
Recommended sequence:
test(frontend): add React component test harnesstest(letter-golf): cover game store and time calculationstest(letter-golf): cover mode, tiles, and played wordstest(frontend): cover feature flags, consent, and ad eligibilitytest(frontend): cover group and settings formstest(frontend): cover standings and victory statestest(frontend): cover navigation and display formatting
Run focused tests after each commit.
Quality Rules¶
- Prefer
screen.getByRole()and accessible names. - Use
userEventfor user interactions. - Use
fireEventonly for low-level events such asanimationEnd. - Use deferred promises to inspect loading states.
- Never make real network calls.
- Restore fake timers, globals, and mocks after every test.
- Avoid broad snapshots.
- Avoid assertions on Radix-generated implementation details.
- Use table-driven tests for error/status matrices and time boundaries.
- Do not silently change product behavior just to make a test pass.
- If a test exposes ambiguous behavior, document it and ask before canonizing it.
- Every regression test should fail if the protected condition is deliberately reversed.
Validation¶
Run:
npm test --prefix .\frontend\minigames
npm run lint --prefix .\frontend\minigames
npx --prefix .\frontend\minigames tsc --noEmit
npm run build --prefix .\frontend\minigames
Report:
- Test files added
- Test count added
- Production helpers extracted
- Any behavior changed
- Any browser-only issue that Vitest cannot conclusively validate
- Any ambiguous product behavior intentionally left without an assertion
Recommended Initial Stopping Point¶
Complete Phases 1 through 4 plus Event Standings in Phase 5. That provides meaningful coverage of gameplay, permissions, consent, forms, destructive actions, time-zone behavior, and UI state transitions without turning the unit-test suite into a simulation of the entire application.
2026-08-23 checkpoint: this initial stopping point has been met and exceeded. Continue adding focused tests beside behavior changes and reported regressions rather than pursuing test count for its own sake. Browser layout, scrolling, responsive geometry, animation timing, real navigation, and third-party provider behavior remain candidates for targeted browser-level checks rather than jsdom assertions.