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

document-navigation.test.ts

303 lines9.8 KB

1import { createBrowserHistory, createMemoryHistory } from '@tanstack/history'
2import { afterEach, describe, expect, test, vi } from 'vitest'
3import { BaseRootRoute, BaseRoute, redirect } from '../src'
4import { createRequestHandler } from '../src/ssr/createRequestHandler'
5import { createTestRouter } from './routerTestUtils'
6import type { RouterHistory } from '@tanstack/history'
7import type { LocationRewrite } from '../src'
8​
9const externalHref = 'https://admin.example.com/dashboard'
10​
11function setupRouter({
12 isServer = false,
13 basepath,
14 history = createMemoryHistory({ initialEntries: ['/'] }),
15 rewrite = {
16 output: ({ url }) => {
17 if (url.pathname === '/admin') {
18 return new URL(externalHref + url.search + url.hash)
19 }
20 return url
21 },
22 },
23}: {
24 isServer?: boolean
25 basepath?: string
26 history?: RouterHistory
27 rewrite?: LocationRewrite
28} = {}) {
29 const rootRoute = new BaseRootRoute()
30 const loader = vi.fn(() => 'admin')
31 const routeTree = rootRoute.addChildren([
32 new BaseRoute({ getParentRoute: () => rootRoute, path: '/' }),
33 new BaseRoute({ getParentRoute: () => rootRoute, path: '/local' }),
34 new BaseRoute({ getParentRoute: () => rootRoute, path: '/admin', loader }),
35 ])
36 const router = createTestRouter({
37 routeTree,
38 history,
39 origin: 'https://example.com',
40 isServer,
41 basepath,
42 rewrite,
43 })
44 const windowLocation = { href: '', replace: vi.fn() }
45 vi.stubGlobal('window', { location: windowLocation })
46​
47 return { router, history, windowLocation, loader }
49​
50afterEach(() => {
51 vi.restoreAllMocks()
52 vi.unstubAllGlobals()
53})
54​
55describe('SSR redirects to cross-origin rewrites', () => {
56 test.each([
57 { hook: 'beforeLoad', statusCode: undefined },
58 { hook: 'beforeLoad', statusCode: 308 },
59 { hook: 'loader', statusCode: undefined },
60 { hook: 'loader', statusCode: 308 },
61 ] as const)(
62 'returns the rewritten HTTP redirect from $hook (statusCode=$statusCode)',
63 async ({ hook, statusCode }) => {
64 const rootRoute = new BaseRootRoute()
65 const throwRedirect = vi.fn(() => {
66 throw redirect({
67 to: '/admin',
68 search: { page: 2 },
69 hash: 'details',
70 statusCode,
71 })
72 })
73 const destinationLoader = vi.fn(() => 'admin')
74 const router = createTestRouter({
75 isServer: true,
76 routeTree: rootRoute.addChildren([
77 new BaseRoute({
78 getParentRoute: () => rootRoute,
79 path: '/redirecting',
80 [hook]: throwRedirect,
81 }),
82 new BaseRoute({
83 getParentRoute: () => rootRoute,
84 path: '/admin',
85 loader: destinationLoader,
86 }),
87 ]),
88 rewrite: {
89 output: ({ url }) => {
90 if (url.pathname === '/admin') {
91 return new URL(externalHref + url.search + url.hash)
92 }
93 return url
94 },
95 },
96 })
97 const render = vi.fn(() => new Response('rendered HTML'))
98 vi.stubGlobal('window', undefined)
99​
100 const response = await createRequestHandler({
101 createRouter: () => router,
102 request: new Request('https://example.com/redirecting'),
103 })(render)
104​
105 expect(throwRedirect).toHaveBeenCalledOnce()
106 expect(response.status).toBe(statusCode ?? 307)
107 expect(response.headers.get('Location')).toBe(
108 `${externalHref}?page=2#details`,
109 )
110 expect(render).not.toHaveBeenCalled()
111 expect(destinationLoader).not.toHaveBeenCalled()
112 },
113 )
114})
115​
116describe('document navigation', () => {
117 test.each([false, true])(
118 'navigates to the final cross-origin output (replace=%s)',
119 async (replace) => {
120 const { router, history, windowLocation, loader } = setupRouter()
121 const push = vi.spyOn(history, 'push')
122 const replaceHistory = vi.spyOn(history, 'replace')
123 const location = router.state.location
124​
125 await router.navigate({
126 to: '/admin',
127 search: { page: 2 },
128 hash: 'details',
129 replace,
130 })
131​
132 const href = `${externalHref}?page=2#details`
133 if (replace) {
134 expect(windowLocation.replace).toHaveBeenCalledWith(href)
135 expect(windowLocation.href).toBe('')
136 } else {
137 expect(windowLocation.href).toBe(href)
138 expect(windowLocation.replace).not.toHaveBeenCalled()
139 }
140 expect(push).not.toHaveBeenCalled()
141 expect(replaceHistory).not.toHaveBeenCalled()
142 expect(loader).not.toHaveBeenCalled()
143 expect(router.state.location).toBe(location)
144 expect(router._commitPromise).toBeUndefined()
145 },
146 )
147​
148 test('commits an external public mask without rebuilding the location', async () => {
149 const { router, history, windowLocation } = setupRouter()
150 const location = router.buildLocation({
151 to: '/local',
152 mask: { to: '/admin', hash: 'masked' },
153 })
154 const buildLocation = vi.spyOn(router, 'buildLocation')
155 const navigate = vi.spyOn(router, 'navigate')
156​
157 await router.commitLocation({ ...location, replace: true })
158​
159 expect(windowLocation.replace).toHaveBeenCalledWith(
160 `${externalHref}#masked`,
161 )
162 expect(history.location.href).toBe('/')
163 expect(buildLocation).not.toHaveBeenCalled()
164 expect(navigate).not.toHaveBeenCalled()
165 })
166​
167 test('uses history for a same-origin mask of an external output', async () => {
168 const { router, history, windowLocation } = setupRouter()
169 await router.load()
170​
171 await router.navigate({ to: '/admin', mask: { to: '/local' } })
172​
173 expect(history.location.href).toBe('/local')
174 expect(router.state.location.pathname).toBe('/admin')
175 expect(router.state.location.maskedLocation?.pathname).toBe('/local')
176 expect(windowLocation.href).toBe('')
177 expect(windowLocation.replace).not.toHaveBeenCalled()
178 })
179​
180 test('ignores server navigation to an external output', async () => {
181 const { router, history } = setupRouter({ isServer: true })
182 vi.stubGlobal('window', undefined)
183​
184 await router.navigate({ to: '/admin' })
185​
186 expect(history.location.href).toBe('/')
187 })
188​
189 test.each([
190 {
191 href: 'https://other.example/a%2fb?value=a+b&value=a%20b#raw%2f',
192 publicHref: '/ignored',
193 },
194 {
195 href: '../target?value=a+b&value=a%20b#raw%2f',
196 reloadDocument: true,
197 },
198 ])('preserves a raw document href: $href', async (options) => {
199 const output = vi.fn(({ url }) => url)
200 const { router, windowLocation } = setupRouter({
201 basepath: '/app',
202 rewrite: { output },
203 })
204 const buildLocation = vi.spyOn(router, 'buildLocation')
205​
206 await router.navigate(options)
207​
208 expect(windowLocation.href).toBe(options.href)
209 expect(buildLocation).not.toHaveBeenCalled()
210 expect(output).not.toHaveBeenCalled()
211 })
212​
213 test.each([undefined, 'https://public.example/prepared'])(
214 'preserves explicit reload publicHref precedence (%s)',
215 async (publicHref) => {
216 const { router, windowLocation } = setupRouter()
217 const buildLocation = vi.spyOn(router, 'buildLocation')
218​
219 await router.navigate({
220 to: '/admin',
221 href: '/admin',
222 publicHref,
223 reloadDocument: true,
224 })
225​
226 expect(windowLocation.href).toBe(publicHref ?? externalHref)
227 expect(buildLocation).toHaveBeenCalledTimes(1)
228 },
229 )
230​
231 describe.each(['memory', 'browser'] as const)(
232 '%s history blockers',
233 (kind) => {
234 test.each([
235 { reloadDocument: false, replace: false },
236 { reloadDocument: false, replace: true },
237 { reloadDocument: true, replace: false },
238 { reloadDocument: true, replace: true },
239 ])(
240 'respects registered blockers and ignoreBlocker (reloadDocument=$reloadDocument, replace=$replace)',
241 async ({ reloadDocument, replace }) => {
242 const history =
243 kind === 'browser'
244 ? createBrowserHistory()
245 : createMemoryHistory({ initialEntries: ['/'] })
246 try {
247 const { router, windowLocation } = setupRouter({ history })
248 const blockerFn = vi.fn(async () => true)
249 history.block({ blockerFn, enableBeforeUnload: false })
250 const location = history.location
251​
252 await router.navigate({ to: '/admin', reloadDocument, replace })
253​
254 expect(blockerFn).toHaveBeenCalledExactlyOnceWith({
255 currentLocation: location,
256 nextLocation: location,
257 action: replace ? 'REPLACE' : 'PUSH',
258 })
259 expect(windowLocation.href).toBe('')
260 expect(windowLocation.replace).not.toHaveBeenCalled()
261 expect(history.location).toBe(location)
262​
263 await router.navigate({
264 to: '/admin',
265 reloadDocument,
266 replace,
267 ignoreBlocker: true,
268 })
269​
270 expect(blockerFn).toHaveBeenCalledTimes(1)
271 if (replace) {
272 expect(windowLocation.replace).toHaveBeenCalledWith(externalHref)
273 expect(windowLocation.href).toBe('')
274 } else {
275 expect(windowLocation.href).toBe(externalHref)
276 expect(windowLocation.replace).not.toHaveBeenCalled()
277 }
278 expect(history.location).toBe(location)
279 } finally {
280 history.destroy()
281 }
282 },
283 )
284 },
285 )
286​
287 test('validates the protocol of an external output before navigating', async () => {
288 const href = 'javascript:alert(1)'
289 const { router, history, windowLocation } = setupRouter({
290 rewrite: { output: () => new URL(href) },
291 })
292 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
293​
294 await router.navigate({ to: '/admin' })
295​
296 expect(windowLocation.href).toBe('')
297 expect(windowLocation.replace).not.toHaveBeenCalled()
298 expect(history.location.href).toBe('/')
299 expect(warn).toHaveBeenCalledWith(
300 `Blocked navigation to dangerous protocol: ${href}`,
301 )
302 })
303})