Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

useMatch.test.tsx

325 lines9.7 KB

1import { useState } from 'react'
2import { afterEach, describe, expect, test, vi } from 'vitest'
3import {
4 cleanup,
5 fireEvent,
6 render,
7 screen,
8 waitFor,
9} from '@testing-library/react'
10import {
11 Link,
12 Outlet,
13 RouterProvider,
14 createMemoryHistory,
15 createRootRoute,
16 createRoute,
17 createRouter,
18 useMatch,
19} from '../src'
20import type { RouteComponent, RouterHistory } from '../src'
21​
22afterEach(() => {
23 window.history.replaceState(null, 'root', '/')
24 cleanup()
25})
26​
27describe('useMatch', () => {
28 function setup({
29 RootComponent,
30 history,
31 }: {
32 RootComponent: RouteComponent
33 history?: RouterHistory
34 }) {
35 const rootRoute = createRootRoute({
36 component: RootComponent,
37 })
38 const indexRoute = createRoute({
39 getParentRoute: () => rootRoute,
40 path: '/',
41 component: () => (
42 <>
43 <h1>IndexTitle</h1>
44 <Link to="/posts">Posts</Link>
45 </>
46 ),
47 })
48​
49 history = history || createMemoryHistory({ initialEntries: ['/'] })
50​
51 const postsRoute = createRoute({
52 getParentRoute: () => rootRoute,
53 path: '/posts',
54 component: () => <h1>PostsTitle</h1>,
55 })
56​
57 const router = createRouter({
58 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
59 history,
60 })
61​
62 return render(<RouterProvider router={router} />)
63 }
64​
65 describe('when match is found', () => {
66 test.each([true, false, undefined])(
67 'returns the match if shouldThrow = %s',
68 async (shouldThrow) => {
69 function RootComponent() {
70 const match = useMatch({ from: '/posts', shouldThrow })
71 expect(match).toBeDefined()
72 expect(match!.routeId).toBe('/posts')
73 return <Outlet />
74 }
75​
76 setup({
77 RootComponent,
78 history: createMemoryHistory({ initialEntries: ['/posts'] }),
79 })
80 const postsTitle = await screen.findByText('PostsTitle')
81 expect(postsTitle).toBeInTheDocument()
82 },
83 )
84​
85 test('returns undefined from select when match is found', async () => {
86 const select = vi.fn(() => undefined)
87​
88 function RootComponent() {
89 const match = useMatch({ from: '/posts', select })
90 expect(match).toBeUndefined()
91 return <Outlet />
92 }
93​
94 setup({
95 RootComponent,
96 history: createMemoryHistory({ initialEntries: ['/posts'] }),
97 })
98 const postsTitle = await screen.findByText('PostsTitle')
99 expect(postsTitle).toBeInTheDocument()
100 expect(select).toHaveBeenCalled()
101 })
102 })
103​
104 test('switches subscriptions when the targeted route changes', async () => {
105 function RootComponent() {
106 const [from, setFrom] = useState('/posts')
107 const routeId = useMatch({
108 from,
109 shouldThrow: false,
110 select: (match) => match.routeId,
111 })
112​
113 return (
114 <>
115 <div data-testid="targeted-route">{routeId ?? 'absent'}</div>
116 <button onClick={() => setFrom('/')}>Select index</button>
117 <button onClick={() => setFrom('/posts')}>Select posts</button>
118 <Outlet />
119 </>
120 )
121 }
122​
123 setup({ RootComponent })
124 expect(await screen.findByText('IndexTitle')).toBeInTheDocument()
125 expect(screen.getByTestId('targeted-route')).toHaveTextContent('absent')
126​
127 fireEvent.click(screen.getByRole('button', { name: 'Select index' }))
128 expect(screen.getByTestId('targeted-route')).toHaveTextContent('/')
129​
130 fireEvent.click(screen.getByRole('button', { name: 'Select posts' }))
131 expect(screen.getByTestId('targeted-route')).toHaveTextContent('absent')
132​
133 fireEvent.click(screen.getByRole('link', { name: 'Posts' }))
134 expect(await screen.findByText('PostsTitle')).toBeInTheDocument()
135 expect(screen.getByTestId('targeted-route')).toHaveTextContent('/posts')
136 })
137​
138 test('tracks presentation generations across replacement and re-entry', async () => {
139 function RootComponent() {
140 const targetedRevision = useMatch({
141 from: '/item',
142 shouldThrow: false,
143 select: (match) => match.loaderData,
144 })
145​
146 return (
147 <>
148 <div data-testid="targeted-match">
149 {targetedRevision === undefined
150 ? 'Targeted absent'
151 : `Targeted revision ${targetedRevision}`}
152 </div>
153 <Link to="/item" search={{ revision: 2 }}>
154 Revision 2
155 </Link>
156 <Link to="/item" search={{ revision: 3 }}>
157 Revision 3
158 </Link>
159 <Link to="/other">Other</Link>
160 <Outlet />
161 </>
162 )
163 }
164​
165 function ItemComponent() {
166 const nearestRevision = useMatch({
167 strict: false,
168 shouldThrow: false,
169 select: (match) => match.loaderData as number,
170 })
171 return <div>Nearest revision {nearestRevision}</div>
172 }
173​
174 const rootRoute = createRootRoute({ component: RootComponent })
175 const itemRoute = createRoute({
176 getParentRoute: () => rootRoute,
177 path: '/item',
178 validateSearch: (search: Record<string, unknown>) => ({
179 revision: Number(search.revision),
180 }),
181 loaderDeps: ({ search }) => ({ revision: search.revision }),
182 loader: ({ deps }) => deps.revision,
183 component: ItemComponent,
184 })
185 const otherRoute = createRoute({
186 getParentRoute: () => rootRoute,
187 path: '/other',
188 component: () => <div>Other route</div>,
189 })
190 const router = createRouter({
191 routeTree: rootRoute.addChildren([itemRoute, otherRoute]),
192 history: createMemoryHistory({ initialEntries: ['/item?revision=1'] }),
193 })
194​
195 render(<RouterProvider router={router} />)
196 expect(await screen.findByText('Nearest revision 1')).toBeInTheDocument()
197 expect(screen.getByTestId('targeted-match')).toHaveTextContent(
198 'Targeted revision 1',
199 )
200​
201 fireEvent.click(screen.getByText('Revision 2'))
202 expect(await screen.findByText('Nearest revision 2')).toBeInTheDocument()
203 expect(screen.getByTestId('targeted-match')).toHaveTextContent(
204 'Targeted revision 2',
205 )
206​
207 fireEvent.click(screen.getByText('Other'))
208 expect(await screen.findByText('Other route')).toBeInTheDocument()
209 expect(screen.getByTestId('targeted-match')).toHaveTextContent(
210 'Targeted absent',
211 )
212​
213 fireEvent.click(screen.getByText('Revision 3'))
214 expect(await screen.findByText('Nearest revision 3')).toBeInTheDocument()
215 expect(screen.getByTestId('targeted-match')).toHaveTextContent(
216 'Targeted revision 3',
217 )
218 })
219​
220 test('renders a route generation that re-enters before an intermediate route renders', async () => {
221 function RootComponent() {
222 return (
223 <>
224 <Link to="/other">Other</Link>
225 <Outlet />
226 </>
227 )
228 }
229​
230 function ItemComponent() {
231 const revision = useMatch({
232 strict: false,
233 select: (match) => match.loaderData as number,
234 })
235 return <div>Item revision {revision}</div>
236 }
237​
238 const rootRoute = createRootRoute({ component: RootComponent })
239 const itemRoute = createRoute({
240 getParentRoute: () => rootRoute,
241 path: '/item',
242 validateSearch: (search: Record<string, unknown>) => ({
243 revision: Number(search.revision),
244 }),
245 loaderDeps: ({ search }) => ({ revision: search.revision }),
246 loader: ({ deps }) => deps.revision,
247 component: ItemComponent,
248 })
249 const otherRoute = createRoute({
250 getParentRoute: () => rootRoute,
251 path: '/other',
252 component: () => <div>Other route</div>,
253 })
254 const router = createRouter({
255 routeTree: rootRoute.addChildren([itemRoute, otherRoute]),
256 history: createMemoryHistory({ initialEntries: ['/item?revision=1'] }),
257 })
258​
259 render(<RouterProvider router={router} />)
260 expect(await screen.findByText('Item revision 1')).toBeInTheDocument()
261​
262 let returnNavigation: Promise<void> | undefined
263 const unsubscribe = router.subscribe('onLoad', (event) => {
264 if (event.toLocation.pathname === '/other') {
265 returnNavigation = router.navigate({
266 to: '/item',
267 search: { revision: 2 },
268 })
269 }
270 })
271 try {
272 fireEvent.click(screen.getByText('Other'))
273 await waitFor(() => expect(returnNavigation).toBeDefined())
274 await returnNavigation
275​
276 expect(await screen.findByText('Item revision 2')).toBeInTheDocument()
277 expect(screen.queryByText('Other route')).not.toBeInTheDocument()
278 } finally {
279 unsubscribe()
280 }
281 })
282​
283 describe('when match is not found', () => {
284 test.each([undefined, true])(
285 'throws if shouldThrow = %s',
286 async (shouldThrow) => {
287 function RootComponent() {
288 useMatch({ from: '/posts', shouldThrow })
289 return <Outlet />
290 }
291 setup({ RootComponent })
292 const postsError = await screen.findByText(
293 'Invariant failed: Could not find an active match from "/posts"',
294 )
295 expect(postsError).toBeInTheDocument()
296 },
297 )
298​
299 describe('returns undefined if shouldThrow = false', () => {
300 test('without select function', async () => {
301 function RootComponent() {
302 const match = useMatch({ from: 'posts', shouldThrow: false })
303 expect(match).toBeUndefined()
304 return <Outlet />
305 }
306 setup({ RootComponent })
307 expect(
308 await waitFor(() => screen.findByText('IndexTitle')),
309 ).toBeInTheDocument()
310 })
311 test('with select function', async () => {
312 const select = vi.fn()
313 function RootComponent() {
314 const match = useMatch({ from: 'posts', shouldThrow: false, select })
315 expect(match).toBeUndefined()
316 return <Outlet />
317 }
318 setup({ RootComponent })
319 const indexTitle = await screen.findByText('IndexTitle')
320 expect(indexTitle).toBeInTheDocument()
321 expect(select).not.toHaveBeenCalled()
322 })
323 })
324 })
325})