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

Matches.test.tsx

244 lines5.9 KB

1import { expect, test } from 'vitest'
2import { fireEvent, render, screen } from '@solidjs/testing-library'
3import { createContext, useContext } from 'solid-js'
4import {
5 Link,
6 Outlet,
7 RouterProvider,
8 createMemoryHistory,
9 createRootRoute,
10 createRoute,
11 createRouter,
12 isMatch,
13 useMatches,
14} from '../src'
15import { sleep } from './utils'
16​
17const rootRoute = createRootRoute()
18​
19const indexRoute = createRoute({
20 getParentRoute: () => rootRoute,
21 path: '/',
22 component: () => {
23 return <Link to="/invoices/">To Invoices</Link>
24 },
25})
26​
27const invoicesRoute = createRoute({
28 getParentRoute: () => rootRoute,
29 path: 'invoices',
30 loader: () => [{ id: '1' }, { id: '2' }],
31 component: () => <Outlet />,
32})
33​
34const InvoicesIndex = () => {
35 const matches = useMatches<DefaultRouter>()
36 console.log('Matchse', matches())
37​
38 const loaderDataMatches = matches().filter((match) =>
39 isMatch(match, 'loaderData.0.id'),
40 )
41​
42 const contextMatches = matches().filter((match) =>
43 isMatch(match, 'context.permissions'),
44 )
45​
46 const incorrectMatches = matches().filter((match) =>
47 isMatch(match, 'loaderData.6.id'),
48 )
49​
50 return (
51 <div>
52 <section>
53 Loader Matches -{' '}
54 {loaderDataMatches.map((match) => match.fullPath).join(',')}
55 </section>
56 <section>
57 Context Matches -{' '}
58 {contextMatches.map((match) => match.fullPath).join(',')}
59 </section>
60 <section>
61 Incorrect Matches -{' '}
62 {incorrectMatches.map((match) => match.fullPath).join(',')}
63 </section>
64 </div>
65 )
67​
68const invoicesIndexRoute = createRoute({
69 getParentRoute: () => invoicesRoute,
70 path: '/',
71 component: InvoicesIndex,
72 context: () => ({
73 permissions: 'permission',
74 }),
75})
76​
77const invoiceRoute = createRoute({
78 getParentRoute: () => invoicesRoute,
79 path: '$invoiceId',
80 validateSearch: () => ({ page: 0 }),
81})
82​
83const layoutRoute = createRoute({
84 getParentRoute: () => rootRoute,
85 id: '_layout',
86})
87​
88const commentsRoute = createRoute({
89 getParentRoute: () => layoutRoute,
90 path: 'comments/$id',
91 validateSearch: () => ({
92 page: 0,
93 search: '',
94 }),
95 loader: () =>
96 [{ comment: 'one comment' }, { comment: 'two comment' }] as const,
97})
98​
99const routeTree = rootRoute.addChildren([
100 invoicesRoute.addChildren([invoicesIndexRoute, invoiceRoute]),
101 indexRoute,
102 layoutRoute.addChildren([commentsRoute]),
103])
104​
105const defaultRouter = createRouter({
106 routeTree,
107})
108​
109type DefaultRouter = typeof defaultRouter
110​
111test('when filtering useMatches by loaderData', async () => {
112 render(() => <RouterProvider router={defaultRouter} />)
113​
114 const searchLink = await screen.findByRole('link', { name: 'To Invoices' })
115​
116 fireEvent.click(searchLink)
117​
118 expect(
119 await screen.findByText('Loader Matches - /invoices'),
120 ).toBeInTheDocument()
121​
122 expect(
123 await screen.findByText('Context Matches - /invoices/'),
124 ).toBeInTheDocument()
125​
126 expect(await screen.findByText('Incorrect Matches -')).toBeInTheDocument()
127})
128​
129test('Matches provides InnerWrap context to route components', async () => {
130 const rootRoute = createRootRoute({
131 component: () => {
132 const contextValue = useContext(ctx)
133 expect(contextValue, 'Context is not provided').not.toBeUndefined()
134​
135 return <div>{contextValue}</div>
136 },
137 })
138​
139 const routeTree = rootRoute.addChildren([])
140 const router = createRouter({
141 routeTree,
142 })
143​
144 const ctx = createContext<string>()
145​
146 const app = render(() => (
147 <RouterProvider
148 router={router}
149 InnerWrap={(props) => {
150 return (
151 <ctx.Provider value={'context-for-children'}>
152 {props.children}
153 </ctx.Provider>
154 )
155 }}
156 />
157 ))
158​
159 const indexElem = await app.findByText('context-for-children')
160 expect(indexElem).toBeInTheDocument()
161})
162​
163test('Matches provides InnerWrap context to defaultPendingComponent', async () => {
164 const rootRoute = createRootRoute({})
165 const indexRoute = createRoute({
166 getParentRoute: () => rootRoute,
167 path: '/',
168 component: () => {
169 return (
170 <div>
171 <Link to="/home">link to home</Link>
172 </div>
173 )
174 },
175 })
176​
177 const homeRoute = createRoute({
178 getParentRoute: () => rootRoute,
179 path: '/home',
180 loader: () => sleep(300),
181 component: () => <div>Home page</div>,
182 })
183​
184 const routeTree = rootRoute.addChildren([homeRoute, indexRoute])
185 const router = createRouter({
186 routeTree,
187 history: createMemoryHistory({
188 initialEntries: ['/'],
189 }),
190 })
191​
192 const ctx = createContext<string>()
193​
194 const app = render(() => (
195 <RouterProvider
196 router={router}
197 defaultPendingMs={200}
198 defaultPendingComponent={() => {
199 const contextValue = useContext(ctx)
200 expect(contextValue, 'Context is not provided').not.toBeUndefined()
201​
202 return <div>{contextValue}</div>
203 }}
204 InnerWrap={(props) => {
205 return (
206 <ctx.Provider value={'context-for-default-pending'}>
207 {props.children}
208 </ctx.Provider>
209 )
210 }}
211 />
212 ))
213​
214 const linkToHome = await app.findByRole('link', {
215 name: 'link to home',
216 })
217 expect(linkToHome).toBeInTheDocument()
218​
219 fireEvent.click(linkToHome)
220​
221 const indexElem = await app.findByText('context-for-default-pending')
222 expect(indexElem).toBeInTheDocument()
223})
224​
225test('should show pendingComponent of root route', async () => {
226 const root = createRootRoute({
227 pendingComponent: () => <div data-testId="root-pending" />,
228 loader: async () => {
229 await new Promise((r) => setTimeout(r, 50))
230 },
231 component: () => <div data-testId="root-content" />,
232 })
233​
234 const router = createRouter({
235 routeTree: root,
236 defaultPendingMs: 0,
237 defaultPendingComponent: () => <div>default pending...</div>,
238 })
239​
240 const rendered = render(() => <RouterProvider router={router} />)
241​
242 expect(await rendered.findByTestId('root-pending')).toBeInTheDocument()
243 expect(await rendered.findByTestId('root-content')).toBeInTheDocument()
244})