Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/__tests__/routes/root-scroll-behavior.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from '../test-render';
import { RouterProvider, createRouter, createRoute } from '@tanstack/react-router';
import { rootRoute } from '../../routes/root';

describe('Root route scroll behavior', () => {
let scrollToSpy: ReturnType<typeof vi.fn>;

beforeEach(() => {
// Mock window.scrollTo
scrollToSpy = vi.fn();
window.scrollTo = scrollToSpy;
});

it('does not scroll to top on preload (hover intent)', async () => {
// Create a simple test route
const testRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/test',
component: () => <div>Test Page</div>,
});

const routeTree = rootRoute.addChildren([testRoute]);
const router = createRouter({
routeTree,
defaultPreload: 'intent',
});

render(<RouterProvider router={router} />);

// Clear any initial scroll calls
scrollToSpy.mockClear();

// Preload the route (simulates hovering over a link)
await router.preloadRoute({ to: '/test' });

// Wait a bit to ensure no scroll happens
await new Promise(resolve => setTimeout(resolve, 100));

// Verify scrollTo was NOT called during preload
expect(scrollToSpy).not.toHaveBeenCalled();
});
});
4 changes: 2 additions & 2 deletions src/routes/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { NavigationProvider } from '../context/NavigationContext';
function RootLayout() {
const router = useRouter();

// Scroll to top on route changes
// Scroll to top on route changes (only on actual navigation, not preload)
useEffect(() => {
const unsubscribe = router.subscribe('onResolved', () => {
const unsubscribe = router.subscribe('onBeforeNavigate', () => {
window.scrollTo(0, 0);
});

Expand Down