Skip to content

Conversation

Dakkers
Copy link

@Dakkers Dakkers commented Jul 20, 2025

As requested by @schiller-manuel for this reported issue: #4696

Summary by CodeRabbit

  • New Features
    • Added support for memory history–based routing, enabling in-memory navigation scenarios without touching the browser history.
  • Tests
    • Added a comprehensive reproduction test covering loader-provided context, authenticated navigation visibility, suspense/pending states, and query handling across routes.

const router = createRouter({ routeTree })

render(<RouterProvider router={router} />)
await act(async () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

replace

await act(async () => {

    /* no-op */
  })

by

await router.load()

Copy link
Contributor

Choose a reason for hiding this comment

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

this applies to all occurences

Copy link
Author

Choose a reason for hiding this comment

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

for some reason when I change it to await router.load() for the index route, the test fails there – it doesn't render the navbar as it did with the act call.

image

when I use await router.load() for the dashboard route part, it doesn't render anything at all:

image

await act(async () => {
/* no-op */
})
expect(screen.getByRole('heading', { name: 'Index' })).toBeInTheDocument()
Copy link
Contributor

Choose a reason for hiding this comment

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

please use getByTestId and use data-testid="..."
we try not to use getByRole in new tests anymore

Copy link
Author

Choose a reason for hiding this comment

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

got it – why's that? (just curious)

Copy link
Contributor

Choose a reason for hiding this comment

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

it allows to change text, tags etc without having to update the getByRole calls
you just need to make sure the test-id is correctly specified

Copy link

nx-cloud bot commented Jul 20, 2025

View your CI Pipeline Execution ↗ for commit d9b8213

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ✅ Succeeded 1m 51s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 3s View ↗

☁️ Nx Cloud last updated this comment at 2025-09-05 17:39:49 UTC

Copy link

pkg-pr-new bot commented Jul 20, 2025

More templates

@tanstack/arktype-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@4726

@tanstack/directive-functions-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@4726

@tanstack/eslint-plugin-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@4726

@tanstack/history

npm i https://pkg.pr.new/TanStack/router/@tanstack/history@4726

@tanstack/react-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@4726

@tanstack/react-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@4726

@tanstack/react-router-ssr-query

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@4726

@tanstack/react-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@4726

@tanstack/react-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@4726

@tanstack/react-start-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@4726

@tanstack/react-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@4726

@tanstack/router-cli

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@4726

@tanstack/router-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@4726

@tanstack/router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@4726

@tanstack/router-devtools-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@4726

@tanstack/router-generator

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@4726

@tanstack/router-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@4726

@tanstack/router-ssr-query-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@4726

@tanstack/router-utils

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@4726

@tanstack/router-vite-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@4726

@tanstack/server-functions-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@4726

@tanstack/solid-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@4726

@tanstack/solid-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@4726

@tanstack/solid-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@4726

@tanstack/solid-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@4726

@tanstack/solid-start-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@4726

@tanstack/solid-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@4726

@tanstack/start-client-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@4726

@tanstack/start-plugin-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@4726

@tanstack/start-server-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@4726

@tanstack/start-server-functions-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@4726

@tanstack/start-server-functions-fetcher

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@4726

@tanstack/start-server-functions-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@4726

@tanstack/start-storage-context

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@4726

@tanstack/valibot-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@4726

@tanstack/virtual-file-routes

npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@4726

@tanstack/zod-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@4726

commit: d9b8213

@Dakkers Dakkers requested a review from schiller-manuel July 21, 2025 14:24
@Dakkers
Copy link
Author

Dakkers commented Aug 8, 2025

@schiller-manuel Is it possible for me to re-run the CI for this PR? It's possible the bug has been fixed

Copy link
Contributor

coderabbitai bot commented Sep 5, 2025

Walkthrough

Adds a new test in loaders.test.tsx reproducing auth-aware navigation rendering with beforeLoad, loader, Suspense, and memory-history navigation. Also exposes createMemoryHistory from the react-router src for use in tests, enabling initialEntries-based routing scenarios.

Changes

Cohort / File(s) Summary
Tests: loader and memory history reproduction
packages/react-router/tests/loaders.test.tsx
Adds a test that sets up a root route with beforeLoad augmenting context, a loader returning context, Suspense wrappers, authenticated nav rendering, child Index and Dashboard routes (with validateSearch), and assertions across normal and memory-history navigations using createMemoryHistory.
Public API: memory history export
packages/react-router/src/...
Exports createMemoryHistory(options) for memory history–based routing, used by the new test to initialize routes with initialEntries.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor T as Test Runner
  participant RR as Router
  participant H as MemoryHistory
  participant R as Root Route
  participant D as Dashboard Route

  T->>RR: createRouter(routeTree)
  T->>H: createMemoryHistory({ initialEntries })
  T->>RR: <RouterProvider history=H />
  activate RR
  RR->>R: beforeLoad(ctx)
  R-->>RR: ctx' { isAuthenticated, isAdmin }
  RR->>R: loader(ctx')
  R-->>RR: loaderData(ctx')
  RR-->>T: render Root (nav if authenticated)

  T->>H: navigate('/dashboard?page=0')
  RR->>D: validateSearch()
  D-->>RR: { page: 0 }
  RR-->>T: render Dashboard (with nav)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through routes with memory bright,
Before I load, I set the light—
Auth in my pouch, a nav in view,
Dashboard beckons, page zero too.
With history in tow, I test and cheer,
Carrots for green checks, spring is here! 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 2

Caution

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

⚠️ Outside diff range comments (1)
packages/react-router/tests/loaders.test.tsx (1)

19-24: Export createMemoryHistory or update tests to import it directly
Tests in packages/react-router/tests/loaders.test.tsx import createMemoryHistory from ../src, but that symbol isn’t currently re-exported in packages/react-router/src/index.ts. Either:

  • Re-export it in the public API (e.g. export { createMemoryHistory } from '@remix-run/router'),
    or
  • Change the tests to import createMemoryHistory directly from its source package (history/@remix-run/router).
♻️ Duplicate comments (1)
packages/react-router/tests/loaders.test.tsx (1)

791-795: Replace no-op act with an awaited router load.

No-op act can race with wrapInSuspense/loader resolution. Await the router’s load to stabilize the DOM before asserting.

-  await act(async () => {})
-  expect(screen.getByTestId('heading-index')).toBeInTheDocument()
-  expect(screen.getByTestId('nav')).toBeInTheDocument()
+  await act(() => router.latestLoadPromise)
+  expect(await screen.findByTestId('heading-index')).toBeInTheDocument()
+  expect(await screen.findByTestId('nav')).toBeInTheDocument()
🧹 Nitpick comments (1)
packages/react-router/tests/loaders.test.tsx (1)

796-807: Prefer render().unmount() over mid-test cleanup() and destroy histories.

Mid-test cleanup() is heavy-handed and can interact oddly with global afterEach(cleanup). Unmount the specific render and, if you keep creating explicit histories, call history.destroy() to avoid leaks.

Example pattern:

const { unmount } = render(<RouterProvider router={router2} />)
await act(() => router2.latestLoadPromise)
unmount()
// optionally: router2.options.history?.destroy?.()
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 741821b and d9b8213.

📒 Files selected for processing (1)
  • packages/react-router/tests/loaders.test.tsx (2 hunks)
🔇 Additional comments (1)
packages/react-router/tests/loaders.test.tsx (1)

734-747: Repro scaffolding looks good.

Clear use of beforeLoad, loader, and Suspense to gate the navbar on auth. No changes requested.

Comment on lines +798 to +805
const historyWithSearchParam = createMemoryHistory({
initialEntries: ['/dashboard?page=0'],
})
render(<RouterProvider history={historyWithSearchParam} router={router} />)
await act(async () => {})
expect(screen.getByTestId('heading-dashboard')).toBeInTheDocument()
expect(screen.getByTestId('nav')).toBeInTheDocument()

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Don’t reuse the same router while swapping histories via RouterProvider; create a new router per history.

Passing history into RouterProvider while keeping the same router instance can desynchronize the router’s internal history from the Provider and cause loaders/Suspense not to resolve as expected. Build a fresh router with the target memory history for each scenario and await latestLoadPromise.

-  const historyWithSearchParam = createMemoryHistory({
-    initialEntries: ['/dashboard?page=0'],
-  })
-  render(<RouterProvider history={historyWithSearchParam} router={router} />)
-  await act(async () => {})
-  expect(screen.getByTestId('heading-dashboard')).toBeInTheDocument()
-  expect(screen.getByTestId('nav')).toBeInTheDocument()
+  const router2 = createRouter({
+    routeTree,
+    history: createMemoryHistory({ initialEntries: ['/dashboard?page=0'] }),
+  })
+  render(<RouterProvider router={router2} />)
+  await act(() => router2.latestLoadPromise)
+  expect(await screen.findByTestId('heading-dashboard')).toBeInTheDocument()
+  expect(await screen.findByTestId('nav')).toBeInTheDocument()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const historyWithSearchParam = createMemoryHistory({
initialEntries: ['/dashboard?page=0'],
})
render(<RouterProvider history={historyWithSearchParam} router={router} />)
await act(async () => {})
expect(screen.getByTestId('heading-dashboard')).toBeInTheDocument()
expect(screen.getByTestId('nav')).toBeInTheDocument()
const router2 = createRouter({
routeTree,
history: createMemoryHistory({ initialEntries: ['/dashboard?page=0'] }),
})
render(<RouterProvider router={router2} />)
await act(() => router2.latestLoadPromise)
expect(await screen.findByTestId('heading-dashboard')).toBeInTheDocument()
expect(await screen.findByTestId('nav')).toBeInTheDocument()
🤖 Prompt for AI Agents
In packages/react-router/tests/loaders.test.tsx around lines 798 to 805, the
test reuses the same router instance while swapping in a new memory history via
RouterProvider which can desynchronize the router's internal history and cause
loaders/Suspense to not resolve; instead construct a fresh router for each
history scenario (createMemoryHistory with the desired initialEntries, build a
new router using that history), render RouterProvider with that new router, and
after rendering await the router's latestLoadPromise (or equivalent promise that
indicates loading finished) before asserting that elements like
heading-dashboard and nav are in the document.

Comment on lines +806 to +816
cleanup()

const historyWithoutSearchParam = createMemoryHistory({
initialEntries: ['/dashboard'],
})
render(<RouterProvider history={historyWithoutSearchParam} router={router} />)
await act(async () => {})
expect(screen.getByTestId('heading-dashboard')).toBeInTheDocument()
// Fails here!
expect(screen.getByTestId('nav')).toBeInTheDocument()
})
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Apply the same fix for the no-search-param case.

Create a third router with /dashboard as the initial entry and await load before asserting. This addresses the current failure.

-  const historyWithoutSearchParam = createMemoryHistory({
-    initialEntries: ['/dashboard'],
-  })
-  render(<RouterProvider history={historyWithoutSearchParam} router={router} />)
-  await act(async () => {})
-  expect(screen.getByTestId('heading-dashboard')).toBeInTheDocument()
-  // Fails here!
-  expect(screen.getByTestId('nav')).toBeInTheDocument()
+  const router3 = createRouter({
+    routeTree,
+    history: createMemoryHistory({ initialEntries: ['/dashboard'] }),
+  })
+  render(<RouterProvider router={router3} />)
+  await act(() => router3.latestLoadPromise)
+  expect(await screen.findByTestId('heading-dashboard')).toBeInTheDocument()
+  expect(await screen.findByTestId('nav')).toBeInTheDocument()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cleanup()
const historyWithoutSearchParam = createMemoryHistory({
initialEntries: ['/dashboard'],
})
render(<RouterProvider history={historyWithoutSearchParam} router={router} />)
await act(async () => {})
expect(screen.getByTestId('heading-dashboard')).toBeInTheDocument()
// Fails here!
expect(screen.getByTestId('nav')).toBeInTheDocument()
})
cleanup()
const router3 = createRouter({
routeTree,
history: createMemoryHistory({ initialEntries: ['/dashboard'] }),
})
render(<RouterProvider router={router3} />)
await act(() => router3.latestLoadPromise)
expect(await screen.findByTestId('heading-dashboard')).toBeInTheDocument()
expect(await screen.findByTestId('nav')).toBeInTheDocument()
})
🤖 Prompt for AI Agents
In packages/react-router/tests/loaders.test.tsx around lines 806 to 816, the
"no-search-param" test renders RouterProvider with a history whose initial entry
is '/dashboard' but does not await the router load, causing the nav assertion to
fail; fix by creating a dedicated router instance for the no-search-param case
using '/dashboard' as the initial entry (i.e., a third router), render
RouterProvider with that router, then await the router/load to finish (use act
or await the navigation promise) before asserting that the heading and nav
elements are in the document.

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.

2 participants