Skip to content

improvement(codebase): migrate tests to dbChainMock, extract react-query hooks#4235

Merged
waleedlatif1 merged 6 commits intostagingfrom
waleedlatif1/codebase-quality-audit-v2
Apr 20, 2026
Merged

improvement(codebase): migrate tests to dbChainMock, extract react-query hooks#4235
waleedlatif1 merged 6 commits intostagingfrom
waleedlatif1/codebase-quality-audit-v2

Conversation

@waleedlatif1
Copy link
Copy Markdown
Collaborator

Summary

  • migrate 97 test files to centralized dbChainMock/dbChainMockFns — remove hoisted chain-wiring boilerplate
  • extend dbChainMock helper in @sim/testing to cover insert/update/delete/transaction/execute patterns
  • extract useGitHubStars and useVoiceSettings react-query hooks from inline fetches
  • centralize additional mocks (authMockFns, hybridAuthMockFns) and update sim-testing docs

Type of Change

  • Improvement

Testing

Tested manually — full test suite (300 files, 5310 tests) passes; type-check and lint pass across all 8 packages

Checklist

  • Code follows project style guidelines
  • Self-reviewed my changes
  • Tests added/updated and passing
  • No new warnings introduced
  • I confirm that I have read and agree to the terms outlined in the Contributor License Agreement (CLA)

…ery hooks

Migrate 97 test files to centralized dbChainMock/dbChainMockFns helpers from
@sim/testing — removes hoisted chain-wiring boilerplate.

Extend dbChainMock to cover insert/update/delete/transaction/execute patterns.
Extract useGitHubStars and useVoiceSettings react-query hooks from inline fetches.
Centralize additional mocks (authMockFns, hybridAuthMockFns) and update docs.
@vercel
Copy link
Copy Markdown

vercel bot commented Apr 19, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
docs Skipped Skipped Apr 19, 2026 6:22pm

Request Review

@cursor
Copy link
Copy Markdown

cursor bot commented Apr 19, 2026

PR Summary

Medium Risk
Medium risk: changes API response shapes for chat auth/OTP flows and refactors chat client fetching to react-query, which could affect deployed chat UX if contracts diverge. Large-scale test mocking migration is broad but should be low runtime risk beyond test reliability.

Overview
Testing refactor: migrates a large set of Vitest suites to the centralized dbChainMock/dbChainMockFns (and related global mocks), removing per-file hoisted chain-wiring and many ad-hoc @sim/logger, @sim/db/schema, and auth/request utils mocks; adds/clarifies docs for the supported DB chains and resetDbChainMock() usage.

Runtime behavior changes: the chat auth endpoints now return full deployed chat config (id/title/description/customizations/authType/outputConfigs) on successful password/email OTP authentication, and the chat client is refactored to use new React Query hooks (useDeployedChatConfig, useChatPasswordAuth, useChatEmailOtp*, useGitHubStars, useVoiceSettings) instead of inline fetch/effects, including cache seeding after auth and a key={identifier} remount on route change.

Reviewed by Cursor Bugbot for commit 3220eea. Configure here.

Comment thread apps/sim/app/chat/[identifier]/chat.tsx Outdated
Comment thread apps/sim/hooks/queries/github-stars.ts Outdated
@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps bot commented Apr 19, 2026

Greptile Summary

This PR migrates 97 test files to the new centralized dbChainMock/dbChainMockFns helper (eliminating per-file vi.hoisted() chain boilerplate), adds centralized hybridAuthMock, and extracts useGitHubStars and useVoiceSettings from inline fetch calls into proper React Query hooks. Both previously reported critical issues with dbChainMock — the mismatched transaction instance and the missing execute on dbChainMock.db — have been fixed in the follow-up commit.

Confidence Score: 5/5

Safe to merge — all prior P0/P1 findings are resolved, remaining items are P2 style and docs suggestions

Both critical bugs flagged in prior threads (wrong transaction instance, missing db.execute) are confirmed fixed. Full test suite (5310 tests) passes. The remaining findings are: a docs wording inconsistency in sim-testing.md, a narrow from() mock gap for queries that skip .where() (documented intentional design, no failing tests), and a minor a11y note. None of these block merge.

packages/testing/src/mocks/database.mock.ts — the from() → terminal shortcut gap is worth noting for future contributors adding queries that skip .where()

Important Files Changed

Filename Overview
packages/testing/src/mocks/database.mock.ts Extends dbChainMock with insert/update/delete/transaction/execute chain support; prior thread bugs (missing execute, mismatched transaction instance) are fixed; from() still lacks direct terminals for queries that skip .where()
packages/testing/src/mocks/hybrid-auth.mock.ts New centralized mock for @/lib/auth/hybrid; default implementation delegates to authMockFns.mockGetSession() so tests that only mock session auth continue to work transparently
apps/sim/hooks/queries/github-stars.ts Extracts inline GitHub stars fetch into a proper React Query hook with 1-hour staleTime and string-typed initialData to eliminate undefined checks in consumers
apps/sim/hooks/queries/voice-settings.ts Extracts voice settings fetch into a React Query hook; returns { sttAvailable: false } on error rather than throwing, keeping STT as a gracefully degraded optional capability
apps/sim/vitest.setup.ts Adds hybridAuthMock to global vi.mock setup; databaseMock remains the global DB baseline and individual test files override with dbChainMock as needed
apps/sim/app/chat/[identifier]/chat.tsx Replaces three inline fetch patterns with useDeployedChatConfig, useVoiceSettings, and useGitHubStars hooks; logic is otherwise unchanged
.claude/rules/sim-testing.md Updated testing docs with dbChainMock/hybridAuthMock patterns; "Global Mocks" section slightly contradicts the database chain override guidance
packages/testing/src/mocks/index.ts Adds exports for dbChainMock, dbChainMockFns, resetDbChainMock, hybridAuthMock, hybridAuthMockFns to the package's public surface

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    subgraph dbChainMock["dbChainMock (centralized)"]
        select["select / selectDistinct / selectDistinctOn"]
        from["from()"]
        joins["innerJoin / leftJoin"]
        where["where()"]
        terminals["limit / orderBy / returning / groupBy"]
        insert["insert()"]
        values["values()"]
        ins_returns["returning / onConflictDoUpdate / onConflictDoNothing"]
        update["update()"]
        set["set()"]
        del["delete()"]
        execute["execute()"]
        transaction["transaction(cb)"]
    end

    select --> from
    from --> joins --> where
    from --> where
    where --> terminals

    insert --> values --> ins_returns

    update --> set --> where
    del --> where

    execute -.->|"resolves []"| done(["Promise.resolve([])"])
    transaction -.->|"calls cb(dbChainMock.db)"| dbChainMock

    subgraph hooks["New React Query Hooks"]
        gh["useGitHubStars\n(staleTime: 1h, initialData: '27.8k')"]
        vs["useVoiceSettings\n(staleTime: 5m, returns sttAvailable:false on error)"]
    end

    gh -->|"/api/stars"| server["Server"]
    vs -->|"/api/settings/voice"| server
Loading

Reviews (5): Last reviewed commit: "fix(chat): reset chat state on identifie..." | Re-trigger Greptile

Comment thread packages/testing/src/mocks/database.mock.ts
Comment thread packages/testing/src/mocks/database.mock.ts
…constants

Move the placeholder star count into useGitHubStars as initialData with
initialDataUpdatedAt: 0 so `data` is always a narrowed string while still
refetching on mount. Fixes two Bugbot issues: stale '25.8k' in chat.tsx
(vs '27.8k' in navbar) and empty-string return in fetchGitHubStars that
bypassed `??` fallbacks in consumers.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
dbChainMock.db.transaction was an inline vi.fn() separate from the exported
dbChainMockFns.transaction, so dbChainMockFns.transaction.mockResolvedValueOnce
and assertions silently targeted the wrong instance. dbChainMock.db also
omitted execute, so tests for any module that calls db.execute (logging-session,
table service, billing balance) would throw TypeError. Both mocks now reference
the module-level constants so overrides and resetDbChainMock affect the same fn.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@waleedlatif1
Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1
Copy link
Copy Markdown
Collaborator Author

@cursor review

Comment thread apps/sim/app/chat/[identifier]/chat.tsx
Comment thread packages/testing/src/mocks/database.mock.ts
…dbChainMock.db

Why:
- Welcome ChatMessage was rebuilt inline each render, producing a fresh
  timestamp and new array identity — cascading to ChatMessageContainer
  and VoiceInterface props on every tick.
- dbChainMockFns exports selectDistinct/selectDistinctOn but the
  dbChainMock.db object omitted them, so tests that stub those builders
  hit undefined on the mocked module.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@waleedlatif1
Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1
Copy link
Copy Markdown
Collaborator Author

@cursor review

Comment thread apps/sim/app/chat/[identifier]/chat.tsx Outdated
The scroll effect's empty dep array meant it ran only on the first
render, when `chatConfig` is still loading and the component returns
`<ChatLoadingState />` — so `messagesContainerRef.current` was null and
the listener was never attached. Depend on the gating conditions that
control which tree renders, so the effect re-runs once the real
container is in the DOM (and re-attaches when toggling in/out of voice
mode).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@waleedlatif1
Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1
Copy link
Copy Markdown
Collaborator Author

@cursor review

Comment thread apps/sim/app/chat/[identifier]/chat.tsx
Keying `<ChatClient>` on `identifier` guarantees a full remount on
route transitions between chats, so `conversationId`, `messages`, and
every other piece of local state start fresh — no reset effect
required.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@waleedlatif1
Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1
Copy link
Copy Markdown
Collaborator Author

@cursor review

Copy link
Copy Markdown

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 3220eea. Configure here.

@waleedlatif1 waleedlatif1 merged commit 5cf7e8d into staging Apr 20, 2026
14 checks passed
@waleedlatif1 waleedlatif1 deleted the waleedlatif1/codebase-quality-audit-v2 branch April 20, 2026 06:05
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