Skip to content

test(svelte-query/createQuery): switch to fake timers, replace 'vi.waitFor' with 'vi.advanceTimersByTimeAsync', and move 'queryClient' to 'beforeEach'#10390

Merged
sukvvon merged 6 commits intomainfrom
test/svelte-query-createQuery-fake-timers
Apr 5, 2026
Merged

test(svelte-query/createQuery): switch to fake timers, replace 'vi.waitFor' with 'vi.advanceTimersByTimeAsync', and move 'queryClient' to 'beforeEach'#10390
sukvvon merged 6 commits intomainfrom
test/svelte-query-createQuery-fake-timers

Conversation

@sukvvon
Copy link
Copy Markdown
Collaborator

@sukvvon sukvvon commented Apr 5, 2026

🎯 Changes

  • Add vi.useFakeTimers() to beforeEach and vi.useRealTimers() to afterEach
  • Move queryClient and queryCache creation from describe-level const to beforeEach for per-test isolation
  • Replace all vi.waitFor with vi.advanceTimersByTimeAsync for deterministic timer control
  • Replace await sleep(N) in test code with await vi.advanceTimersByTimeAsync(N)
  • Replace await query.refetch() with query.refetch() + await vi.advanceTimersByTimeAsync(0)
  • Rename shadowed queryClient variable to currentClient to fix ESLint warning
  • Remove unnecessary async from withEffectRoot callback without await

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • Tests

    • Made tests isolated per-case to avoid cross-test interference.
    • Switched to fake timers with explicit, deterministic advances for more reliable and faster assertions.
    • Removed flaky async waits in favor of direct state assertions after controlled timer progression.
  • Chores

    • Test maintenance and reliability improvements; no user-facing changes.

…itFor' with 'vi.advanceTimersByTimeAsync', and move 'queryClient' to 'beforeEach'
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 5, 2026

📝 Walkthrough

Walkthrough

Refactors Svelte Query tests to use Vitest fake timers (vi.useFakeTimers()/vi.advanceTimersByTimeAsync()/vi.useRealTimers()), initialize a fresh QueryClient/QueryCache per test, replace waitFor/sleep with deterministic timer advances, adjust refetch timing, and rename a reactive queryClient to currentClient in one test.

Changes

Cohort / File(s) Summary
Svelte Query test updates
packages/svelte-query/tests/createQuery.svelte.test.ts
Tests now enable fake timers in beforeEach and restore in afterEach; create per-test QueryClient/QueryCache; replace vi.waitFor(...)/sleep(...) with vi.advanceTimersByTimeAsync(...); change some await query.refetch() usages to non-awaited query.refetch() + timer advances; adjust one withEffectRoot callback and rename reactive queryClientcurrentClient.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐇
I hopped through tests with nimble feet,
Stopped the clocks to make timing neat,
New clients wake for every race,
I fast‑forwarded time and set the pace,
Tests now hum—a tidy, steady beat.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately describes the main changes: switching to fake timers, replacing vi.waitFor with vi.advanceTimersByTimeAsync, and moving queryClient to beforeEach hooks.
Description check ✅ Passed The PR description includes all required template sections with detailed change descriptions, completed checklist items, and correct release impact assessment (dev-only).
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test/svelte-query-createQuery-fake-timers

Comment @coderabbitai help to get the list of available commands and usage tips.

@sukvvon sukvvon self-assigned this Apr 5, 2026
@nx-cloud
Copy link
Copy Markdown

nx-cloud bot commented Apr 5, 2026

View your CI Pipeline Execution ↗ for commit c99fe97

Command Status Duration Result
nx run-many --target=build --exclude=examples/*... ✅ Succeeded <1s View ↗
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 29s View ↗

☁️ Nx Cloud last updated this comment at 2026-04-05 12:44:19 UTC

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 5, 2026

🚀 Changeset Version Preview

No changeset entries found. Merging this PR will not cause a version bump for any packages.

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Apr 5, 2026

More templates

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/TanStack/query/@tanstack/angular-query-experimental@10390

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/TanStack/query/@tanstack/eslint-plugin-query@10390

@tanstack/preact-query

npm i https://pkg.pr.new/TanStack/query/@tanstack/preact-query@10390

@tanstack/preact-query-devtools

npm i https://pkg.pr.new/TanStack/query/@tanstack/preact-query-devtools@10390

@tanstack/preact-query-persist-client

npm i https://pkg.pr.new/TanStack/query/@tanstack/preact-query-persist-client@10390

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/TanStack/query/@tanstack/query-async-storage-persister@10390

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/TanStack/query/@tanstack/query-broadcast-client-experimental@10390

@tanstack/query-core

npm i https://pkg.pr.new/TanStack/query/@tanstack/query-core@10390

@tanstack/query-devtools

npm i https://pkg.pr.new/TanStack/query/@tanstack/query-devtools@10390

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/TanStack/query/@tanstack/query-persist-client-core@10390

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/TanStack/query/@tanstack/query-sync-storage-persister@10390

@tanstack/react-query

npm i https://pkg.pr.new/TanStack/query/@tanstack/react-query@10390

@tanstack/react-query-devtools

npm i https://pkg.pr.new/TanStack/query/@tanstack/react-query-devtools@10390

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/TanStack/query/@tanstack/react-query-next-experimental@10390

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/TanStack/query/@tanstack/react-query-persist-client@10390

@tanstack/solid-query

npm i https://pkg.pr.new/TanStack/query/@tanstack/solid-query@10390

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/TanStack/query/@tanstack/solid-query-devtools@10390

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/TanStack/query/@tanstack/solid-query-persist-client@10390

@tanstack/svelte-query

npm i https://pkg.pr.new/TanStack/query/@tanstack/svelte-query@10390

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/TanStack/query/@tanstack/svelte-query-devtools@10390

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/TanStack/query/@tanstack/svelte-query-persist-client@10390

@tanstack/vue-query

npm i https://pkg.pr.new/TanStack/query/@tanstack/vue-query@10390

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/TanStack/query/@tanstack/vue-query-devtools@10390

commit: c99fe97

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 5, 2026

size-limit report 📦

Path Size
react full 11.98 KB (0%)
react minimal 9.01 KB (0%)

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
packages/svelte-query/tests/createQuery.svelte.test.ts (2)

86-87: Consider extracting a helper for repeated zero-time timer flushes.

await vi.advanceTimersByTimeAsync(0) appears many times; a tiny helper would reduce duplication and improve readability.

✨ Optional DRY helper
 describe('createQuery', () => {
+  const flushQueryUpdates = () => vi.advanceTimersByTimeAsync(0)

Then replace repeated calls, e.g.:

-      await vi.advanceTimersByTimeAsync(0)
+      await flushQueryUpdates()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/svelte-query/tests/createQuery.svelte.test.ts` around lines 86 - 87,
The test repeats await vi.advanceTimersByTimeAsync(0) in
createQuery.svelte.test.ts; extract a small helper (e.g., flushTimers or
advanceZero) and replace each direct call with that helper to reduce duplication
and clarify intent—add the helper near the top of the test file (or test utils)
and update all occurrences of vi.advanceTimersByTimeAsync(0) within tests to
call the new helper function.

26-29: Restore real timers in a finally block to prevent cascading test pollution.

If queryClient.clear() ever throws, subsequent tests can stay on fake timers.

♻️ Suggested hardening
  afterEach(() => {
-    queryClient.clear()
-    vi.useRealTimers()
+    try {
+      queryClient.clear()
+    } finally {
+      vi.useRealTimers()
+    }
  })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/svelte-query/tests/createQuery.svelte.test.ts` around lines 26 - 29,
The afterEach hook can leave fake timers enabled if queryClient.clear() throws;
wrap the clear call in a try/finally so vi.useRealTimers() always runs. Update
the afterEach to call queryClient.clear() (await if it can return a promise)
inside a try block and call vi.useRealTimers() in the finally block to guarantee
timer restoration (referencing the existing afterEach, queryClient.clear, and
vi.useRealTimers symbols).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/svelte-query/tests/createQuery.svelte.test.ts`:
- Around line 86-87: The test repeats await vi.advanceTimersByTimeAsync(0) in
createQuery.svelte.test.ts; extract a small helper (e.g., flushTimers or
advanceZero) and replace each direct call with that helper to reduce duplication
and clarify intent—add the helper near the top of the test file (or test utils)
and update all occurrences of vi.advanceTimersByTimeAsync(0) within tests to
call the new helper function.
- Around line 26-29: The afterEach hook can leave fake timers enabled if
queryClient.clear() throws; wrap the clear call in a try/finally so
vi.useRealTimers() always runs. Update the afterEach to call queryClient.clear()
(await if it can return a promise) inside a try block and call
vi.useRealTimers() in the finally block to guarantee timer restoration
(referencing the existing afterEach, queryClient.clear, and vi.useRealTimers
symbols).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4afd8ea2-bba2-4398-8978-62e2f9fd861d

📥 Commits

Reviewing files that changed from the base of the PR and between f8e7164 and e87f1aa.

📒 Files selected for processing (1)
  • packages/svelte-query/tests/createQuery.svelte.test.ts

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/svelte-query/tests/createQuery.svelte.test.ts (1)

1296-1305: ⚠️ Potential issue | 🔴 Critical

Test will deadlock when enabled due to awaiting prefetchQuery before advancing fake timers.

Line 1296 awaits prefetchQuery before advancing fake timers at line 1304, but the queryFn's await sleep(10) cannot resolve under fake timers until timers are advanced. This creates a circular dependency that will hang the test when it.todo is converted to it.

Move the await to after timer advancement:

🔧 Fix
-      await queryClient.prefetchQuery({
+      const prefetchPromise = queryClient.prefetchQuery({
         queryKey: key,
         queryFn: async () => {
           await sleep(10)
           return 'prefetch'
         },
       })
 
       await vi.advanceTimersByTimeAsync(10)
+      await prefetchPromise
       expect(queryClient.getQueryState(key)?.data).toBe('prefetch')
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/svelte-query/tests/createQuery.svelte.test.ts` around lines 1296 -
1305, The test deadlocks because it awaits queryClient.prefetchQuery (which runs
queryFn that awaits sleep(10) under fake timers) before advancing timers;
instead, start the prefetch without awaiting (call
queryClient.prefetchQuery(...) and store the returned promise), then call
vi.advanceTimersByTimeAsync(10) to let sleep(10) resolve, and only after
advancing timers await the stored prefetch promise and then assert via
queryClient.getQueryState(key)?.data; adjust the test to use this order using
the existing symbols queryClient.prefetchQuery, vi.advanceTimersByTimeAsync,
sleep, and queryClient.getQueryState.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/svelte-query/tests/createQuery.svelte.test.ts`:
- Around line 1296-1305: The test deadlocks because it awaits
queryClient.prefetchQuery (which runs queryFn that awaits sleep(10) under fake
timers) before advancing timers; instead, start the prefetch without awaiting
(call queryClient.prefetchQuery(...) and store the returned promise), then call
vi.advanceTimersByTimeAsync(10) to let sleep(10) resolve, and only after
advancing timers await the stored prefetch promise and then assert via
queryClient.getQueryState(key)?.data; adjust the test to use this order using
the existing symbols queryClient.prefetchQuery, vi.advanceTimersByTimeAsync,
sleep, and queryClient.getQueryState.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7e55e8f1-84f1-405c-8b51-256fbbd5a271

📥 Commits

Reviewing files that changed from the base of the PR and between e87f1aa and fa3c9da.

📒 Files selected for processing (1)
  • packages/svelte-query/tests/createQuery.svelte.test.ts

@sukvvon sukvvon marked this pull request as draft April 5, 2026 12:31
@sukvvon sukvvon marked this pull request as ready for review April 5, 2026 12:42
@sukvvon sukvvon merged commit 3a993e6 into main Apr 5, 2026
8 checks passed
@sukvvon sukvvon deleted the test/svelte-query-createQuery-fake-timers branch April 5, 2026 12:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant