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

useMatch.test.tsx

270 lines7.9 KB

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