Open History to see the last commit
1import { useEffect } from 'react'
2import { afterEach, describe, expect, test, vi } from 'vitest'
3import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
4import {
5 Outlet,
6 RouterProvider,
7 createMemoryHistory,
8 createRootRoute,
9 createRoute,
10 createRouter,
11 useLocation,
12} from '../src'
13β
14afterEach(() => {
15 window.history.replaceState(null, 'root', '/')
16 cleanup()
17})
18β
19describe('useLocation', () => {
20 test('keeps a selected pathname reference stable across search and hash updates when structural sharing is enabled', async () => {
21 const effectSpy = vi.fn()
22 const pathnameSelections: Array<{ pathname: string }> = []
23β
24 const rootRoute = createRootRoute({
25 component: function RootComponent() {
26 const pathnameSelection = useLocation({
27 select: (location) => ({ pathname: location.pathname }),
28 })
29β
30 useEffect(() => {
31 effectSpy(pathnameSelection)
32 pathnameSelections.push(pathnameSelection)
33 }, [pathnameSelection])
34β
35 return <Outlet />
36 },
37 })
38β
39 const postsRoute = createRoute({
40 getParentRoute: () => rootRoute,
41 path: '/posts',
42 component: () => <h1>Posts</h1>,
43 })
44β
45 const router = createRouter({
46 routeTree: rootRoute.addChildren([postsRoute]),
47 history: createMemoryHistory({
48 initialEntries: ['/posts?foo=one#first'],
49 }),
50 defaultStructuralSharing: true,
51 })
52β
53 render(<RouterProvider router={router} />)
54β
55 expect(
56 await screen.findByRole('heading', { name: 'Posts' }),
57 ).toBeInTheDocument()
58β
59 await waitFor(() => expect(effectSpy).toHaveBeenCalledTimes(1))
60β
61 const initialPathnameSelection = pathnameSelections[0]
62β
63 await act(() =>
64 router.navigate({
65 to: '/posts',
66 search: { foo: 'two' },
67 hash: 'first',
68 }),
69 )
70β
71 await waitFor(() => {
72 expect(router.state.location.search).toEqual({ foo: 'two' })
73 expect(effectSpy).toHaveBeenCalledTimes(1)
74 })
75β
76 await act(() =>
77 router.navigate({
78 to: '/posts',
79 search: { foo: 'two' },
80 hash: 'second',
81 }),
82 )
83β
84 await waitFor(() => {
85 expect(router.state.location.hash).toBe('second')
86 expect(effectSpy).toHaveBeenCalledTimes(1)
87 })
88β
89 expect(pathnameSelections).toHaveLength(1)
90 expect(pathnameSelections[0]).toBe(initialPathnameSelection)
91 })
92})