Skip to content

Conversation

@sukvvon
Copy link
Contributor

@sukvvon sukvvon commented Nov 10, 2025

🎯 Changes

βœ… 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
    • Updated tests to use fake timers and explicit timer advancement instead of sleep/waitFor, making async flows deterministic.
    • Replaced waitFor-based assertions with direct DOM checks driven by timer progression to observe intermediate states (idle β†’ hydrated β†’ fetched β†’ updated).
    • Converted async patterns to timer-driven promises and synchronized persistence restoration in tests.
    • Added coverage for StrictMode and multi-client scenarios.

@changeset-bot
Copy link

changeset-bot bot commented Nov 10, 2025

⚠️ No Changeset found

Latest commit: 6d43ba3

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 10, 2025

Walkthrough

Tests refactored to use fake timers and explicit timer advancement; waitFor and sleep-based delays replaced by timer-driven promise chains and direct DOM assertions; persistence restore synchronization added via a restoration Promise; additional StrictMode and multi-client scenarios covered.

Changes

Cohort / File(s) Summary
Test harness refactor
packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx
Added fake timers in beforeEach/afterEach; replaced waitFor and sleep delays with vi.advanceTimersByTimeAsync and direct DOM assertions; converted queryFn implementations from async/await to promise chains; introduced state/restore Promises for persister.restoreClient synchronization; added tests for StrictMode and multiple-client scenarios and adjusted timer-driven state transitions (idle β†’ hydrated β†’ fetched β†’ updated).

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Test
    participant FakeTimer as Fake Timer (vi)
    participant Persister
    participant QueryClient
    participant DOM

    Note over Test,FakeTimer: Test sets up fake timers and mounts provider
    Test->>Persister: call .restoreClient()
    Persister-->>Test: returns restorePromise (pending)
    Test->>QueryClient: register queries (queryFn returns Promise via sleep.then(...))
    Note over FakeTimer,QueryClient: No real time passes until timers advanced
    Test->>FakeTimer: advanceTimersByTimeAsync(x)
    FakeTimer->>QueryClient: timers fire, queryFns resolve
    QueryClient->>DOM: update UI states ("hydrated","fetched","updated")
    DOM-->>Test: render updates asserted via toBeInTheDocument
    Note over Test: Repeat advances to drive subsequent state transitions
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Check correctness of fake-timer setup/teardown and that async test helpers use async/await with advanceTimersByTimeAsync.
  • Verify promise-chain conversions preserve timing and rejection/resolve behavior.
  • Confirm restore Promise usage correctly synchronizes persistence restore before assertions.

Possibly related PRs

Poem

🐰 Timers set, the tick is neat,

Tests proceed with steady beat.
Promises chain and states align,
Hydrated, fetched β€” assertions fine.
A rabbit nods: the clocks behave! πŸ₯•

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete; the 'Changes' section is empty despite the title and objectives indicating significant test modifications. Required details about what was changed and why are missing. Fill in the 'Changes' section with a description of the test modifications (fake timers, timer advancement, promise patterns) and their motivation for improving test reliability.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
βœ… Passed checks (1 passed)
Check name Status Explanation
Title check βœ… Passed The title accurately and specifically describes the main changes: switching to fake timers, replacing await with advanceTimersByTimeAsync, and using the sleep().then() pattern in the PersistQueryClientProvider tests.
✨ Finishing touches
  • πŸ“ Generate docstrings
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

πŸ“œ Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 810b079 and 6d43ba3.

πŸ“’ Files selected for processing (1)
  • packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx (24 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx (2)
packages/query-persist-client-core/src/__tests__/utils.ts (1)
  • createMockPersister (5-20)
packages/query-persist-client-core/src/persist.ts (1)
  • persistQueryClientSave (114-127)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Preview
  • GitHub Check: Test
πŸ”‡ Additional comments (4)
packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx (4)

53-59: LGTM! Proper fake timer setup.

The beforeEach/afterEach hooks correctly establish and tear down fake timers for deterministic async testing.


24-26: LGTM! Pattern aligns with PR objectives.

The conversion from async/await to sleep().then() pattern is correct and consistent with the PR's goals.


61-796: Excellent test refactoring with fake timers.

The migration to fake timers is comprehensive and well-executed:

  • Proper use of act() around timer advances for React state updates
  • Direct assertions with toBeInTheDocument() provide clearer test intent than waitFor
  • Timer-driven flow (idle β†’ hydrated β†’ fetched) is consistent across all test cases
  • Good coverage of edge cases including StrictMode, multiple clients, error handling, and callback synchronization

The deterministic nature of fake timers will improve test reliability and execution speed.


107-107: Add a comment explaining the 11ms timer advancement for fetch completion.

The pattern await act(() => vi.advanceTimersByTimeAsync(11)) appears in 9 test locations (lines 107, 190, 254, 334, 484, 542, 594, 685, 791) following the 10ms hydration advance. Since the queryFn uses sleep(10), the extra 1ms appears intentional but lacks documentation.

Add a comment explaining whether the 1ms accounts for Promise microtasks, React rendering cycles, or serves as a safety margin. Alternatively, verify that 10ms is insufficient before increasing to 11ms.


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

@nx-cloud
Copy link

nx-cloud bot commented Nov 10, 2025

View your CI Pipeline Execution β†— for commit 6d43ba3

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... βœ… Succeeded 1m 36s View β†—
nx run-many --target=build --exclude=examples/*... βœ… Succeeded 6s View β†—

☁️ Nx Cloud last updated this comment at 2025-11-10 16:40:51 UTC

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 10, 2025

More templates

@tanstack/angular-query-experimental

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

@tanstack/eslint-plugin-query

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

@tanstack/query-async-storage-persister

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

@tanstack/query-broadcast-client-experimental

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

@tanstack/query-core

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

@tanstack/query-devtools

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

@tanstack/query-persist-client-core

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

@tanstack/query-sync-storage-persister

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

@tanstack/react-query

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

@tanstack/react-query-devtools

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

@tanstack/react-query-next-experimental

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

@tanstack/react-query-persist-client

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

@tanstack/solid-query

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

@tanstack/solid-query-devtools

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

@tanstack/solid-query-persist-client

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

@tanstack/svelte-query

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

@tanstack/svelte-query-devtools

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

@tanstack/svelte-query-persist-client

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

@tanstack/vue-query

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

@tanstack/vue-query-devtools

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

commit: 6d43ba3

@codecov
Copy link

codecov bot commented Nov 10, 2025

Codecov Report

βœ… All modified and coverable lines are covered by tests.
βœ… Project coverage is 100.00%. Comparing base (7783a7a) to head (6d43ba3).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff              @@
##             main     #9859       +/-   ##
============================================
+ Coverage   45.76%   100.00%   +54.23%     
============================================
  Files         200         1      -199     
  Lines        8410        18     -8392     
  Branches     1930         2     -1928     
============================================
- Hits         3849        18     -3831     
+ Misses       4113         0     -4113     
+ Partials      448         0      -448     
Components Coverage Ξ”
@tanstack/angular-query-experimental βˆ… <ΓΈ> (βˆ…)
@tanstack/eslint-plugin-query βˆ… <ΓΈ> (βˆ…)
@tanstack/query-async-storage-persister βˆ… <ΓΈ> (βˆ…)
@tanstack/query-broadcast-client-experimental βˆ… <ΓΈ> (βˆ…)
@tanstack/query-codemods βˆ… <ΓΈ> (βˆ…)
@tanstack/query-core βˆ… <ΓΈ> (βˆ…)
@tanstack/query-devtools βˆ… <ΓΈ> (βˆ…)
@tanstack/query-persist-client-core βˆ… <ΓΈ> (βˆ…)
@tanstack/query-sync-storage-persister βˆ… <ΓΈ> (βˆ…)
@tanstack/query-test-utils βˆ… <ΓΈ> (βˆ…)
@tanstack/react-query βˆ… <ΓΈ> (βˆ…)
@tanstack/react-query-devtools βˆ… <ΓΈ> (βˆ…)
@tanstack/react-query-next-experimental βˆ… <ΓΈ> (βˆ…)
@tanstack/react-query-persist-client 100.00% <ΓΈ> (ΓΈ)
@tanstack/solid-query βˆ… <ΓΈ> (βˆ…)
@tanstack/solid-query-devtools βˆ… <ΓΈ> (βˆ…)
@tanstack/solid-query-persist-client βˆ… <ΓΈ> (βˆ…)
@tanstack/svelte-query βˆ… <ΓΈ> (βˆ…)
@tanstack/svelte-query-devtools βˆ… <ΓΈ> (βˆ…)
@tanstack/svelte-query-persist-client βˆ… <ΓΈ> (βˆ…)
@tanstack/vue-query βˆ… <ΓΈ> (βˆ…)
@tanstack/vue-query-devtools βˆ… <ΓΈ> (βˆ…)
πŸš€ New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • πŸ“¦ JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sukvvon sukvvon marked this pull request as ready for review November 10, 2025 16:30
Copy link
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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx (1)

75-76: Consider awaiting persistQueryClientSave for clarity and error handling.

The pattern of calling persistQueryClientSave without await followed by await vi.advanceTimersByTimeAsync(0) works in this test context, but it could lead to unhandled promise rejections if persistQueryClientSave throws an error. For better clarity and error handling, consider:

-    persistQueryClientSave({ queryClient, persister })
-    await vi.advanceTimersByTimeAsync(0)
+    await persistQueryClientSave({ queryClient, persister })

This pattern appears throughout the test file at lines 75-76, 150-151, 218-219, 298-299, 378-379, 449-450, 501-502, 620-621, and 758-759.

πŸ“œ Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between f7c9526 and 810b079.

πŸ“’ Files selected for processing (1)
  • packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx (24 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx (2)
packages/query-persist-client-core/src/__tests__/utils.ts (1)
  • createMockPersister (5-20)
packages/query-persist-client-core/src/persist.ts (1)
  • persistQueryClientSave (114-127)
πŸ”‡ Additional comments (9)
packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.tsx (9)

54-60: LGTM!

The fake timer setup and teardown is correctly implemented following vitest best practices.


17-31: LGTM!

The conversion from async/await to promise chaining (sleep().then()) aligns with the PR objectives and works correctly with fake timers.


33-51: LGTM!

The error persister correctly uses promise chaining to simulate a delayed throw, which integrates well with the fake timer approach.


62-136: LGTM!

The test correctly implements the fake timer pattern:

  • Initial prefetch and persistence setup with appropriate timer advances
  • Restoration and fetching sequences driven by explicit timer controls
  • Proper use of act() for timer advances after component mount

The use of 11ms (instead of exactly 10ms) for the fetch advance is intentional to account for React render cycles and microtasks, which helps prevent flakiness.


198-200: LGTM!

The pattern of capturing the promise before advancing timers is the correct approach with fake timers:

const statePromise = persister.restoreClient()
await act(() => vi.advanceTimersByTimeAsync(10))
const state = await statePromise

This ensures the timer advances before awaiting the result, avoiding the need for multiple timer advances.


511-516: Verify: Intentional use of async/await pattern.

This test uses async/await in the queryFn while all other tests use promise chaining (sleep().then()). Given the test name "should await onSuccess after successful restoring" and that the onSuccess handler also uses async/await (lines 531-535), this appears intentional to verify that async/await patterns work correctly with fake timers.

If this is intentional to provide coverage for both patterns, consider adding a comment explaining why this test differs from others. Otherwise, consider converting to promise chaining for consistency:

-        queryFn: async () => {
-          states.push('fetching')
-          await sleep(10)
-          states.push('fetched')
-          return 'fetched'
-        },
+        queryFn: () =>
+          sleep(0).then(() => {
+            states.push('fetching')
+            return sleep(10)
+          }).then(() => {
+            states.push('fetched')
+            return 'fetched'
+          }),

205-435: LGTM!

These tests correctly implement the fake timer pattern with:

  • Consistent use of promise chaining in queryFn implementations
  • Appropriate timer advances for restoration and fetching sequences
  • Correct verification of query states and fetch behaviors

437-605: LGTM!

These tests properly validate the onSuccess and error handling workflows:

  • onSuccess callback is verified to fire after restoration
  • Error paths correctly trigger removeClient and onError
  • Timer advances account for both restoration and callback delays

607-797: LGTM!

The multiple-client and StrictMode tests are well-structured:

  • Multiple client scenario correctly verifies that only the second client's queryFn is called after hydration
  • StrictMode test validates single restoration despite React 19's double-mounting behavior
  • Both tests properly use fake timers to drive the async flows

…o fake timers, replace 'await' with 'advanceTimersByTimeAsync', and use 'sleep().then()' pattern
@sukvvon sukvvon force-pushed the test/react-query-persist-client-persist-query-client-provider-fake-timers branch from 810b079 to 6d43ba3 Compare November 10, 2025 16:38
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