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

document-navigation-blocking.test.ts

218 lines6.4 KB

1import { URL as NodeURL } from 'node:url'
2import { createBrowserHistory, createHashHistory } from '@tanstack/history'
3import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
4import { BaseRootRoute } from '../src'
5import { createTestRouter } from './routerTestUtils'
6​
7afterEach(() => {
8 vi.unstubAllGlobals()
9})
10​
11function setupDocumentNavigation({
12 initialHref = '/current?query=1#same',
13 baseHref,
14 hashHistory = false,
15}: {
16 initialHref?: string
17 baseHref?: string
18 hashHistory?: boolean
19} = {}) {
20 const browserWindow = window
21 const originalHref = browserWindow.location.href
22 const originalState = browserWindow.history.state
23 browserWindow.history.replaceState(null, '', initialHref)
24 const base = baseHref ? document.createElement('base') : undefined
25 if (base) {
26 base.href = baseHref!
27 document.head.prepend(base)
28 }
29 const history = (hashHistory ? createHashHistory : createBrowserHistory)({
30 window: browserWindow,
31 })
32 onTestFinished(() => {
33 history.destroy()
34 base?.remove()
35 browserWindow.history.replaceState(originalState, '', originalHref)
36 })
37 const blockerFn = vi.fn(() => false)
38 history.block({ blockerFn, enableBeforeUnload: true })
39​
40 // Preserve native URL parse failures, but emit no navigation events. The
41 // first beforeunload we dispatch then belongs to a later attempt to leave.
42 const assign = vi.fn((href: string) => {
43 new NodeURL(href, browserWindow.document.baseURI)
44 })
45 const replace = vi.fn((href: string) => assign(href))
46 vi.stubGlobal('window', {
47 location: {
48 get href() {
49 return browserWindow.location.href
50 },
51 set href(href: string) {
52 assign(href)
53 },
54 replace,
55 },
56 })
57 const router = createTestRouter({
58 routeTree: new BaseRootRoute(),
59 history,
60 origin: browserWindow.location.origin,
61 protocolAllowlist: [
62 'http:',
63 'https:',
64 'mailto:',
65 'tel:',
66 'custom:',
67 'httpx:',
68 ],
69 isServer: false,
70 })
71 const dispatchBeforeUnload = () => {
72 const event = new browserWindow.Event('beforeunload', {
73 cancelable: true,
74 })
75 browserWindow.dispatchEvent(event)
76 return event.defaultPrevented
77 }
78 return {
79 router,
80 browserWindow,
81 assign,
82 replace,
83 blockerFn,
84 dispatchBeforeUnload,
85 }
87​
88describe.each([false, true])(
89 'document navigation with replace=%j',
90 (replace) => {
91 it.each(['https://[', 'https://example.com:99999/', ' \tHt\nTpS://['])(
92 'preserves the next unload warning when %j throws',
93 async (href) => {
94 const { router, assign, dispatchBeforeUnload } =
95 setupDocumentNavigation()
96​
97 await expect(router.navigate({ href, replace })).rejects.toThrow()
98​
99 expect(assign).toHaveBeenCalledWith(href)
100 expect(dispatchBeforeUnload()).toBe(true)
101 },
102 )
103​
104 it.each([
105 'mailto:user@example.com',
106 'tel:+15555550100',
107 'custom:target',
108 'httpx://example.com/',
109 ' \tMa\niLtO:user@example.com',
110 '#same',
111 '#changed',
112 '#',
113 '/current?query=1#same',
114 '/folder/../current?query=1#same',
115 '/current?query=1#mailto:user@example.com',
116 ])('preserves the next unload warning after %j', async (href) => {
117 const { router, assign, blockerFn, dispatchBeforeUnload } =
118 setupDocumentNavigation()
119​
120 await router.navigate({ href, reloadDocument: true, replace })
121​
122 expect(assign).toHaveBeenCalledWith(href)
123 expect(blockerFn).toHaveBeenCalledOnce()
124 expect(dispatchBeforeUnload()).toBe(true)
125 })
126​
127 it('preserves the next unload warning after an unchanged empty fragment', async () => {
128 const { router, dispatchBeforeUnload } = setupDocumentNavigation({
129 initialHref: '/current?query=1#',
130 })
131​
132 await router.navigate({ href: '#', reloadDocument: true, replace })
133​
134 expect(dispatchBeforeUnload()).toBe(true)
135 })
136​
137 it('compares absolute fragment destinations with the visible hash-history URL', async () => {
138 const { router, browserWindow, dispatchBeforeUnload } =
139 setupDocumentNavigation({
140 initialHref: '/shell?query=1#/route',
141 hashHistory: true,
142 })
143​
144 await router.navigate({ href: browserWindow.location.href, replace })
145​
146 expect(dispatchBeforeUnload()).toBe(true)
147 })
148​
149 it.each([
150 'https://other.example/next#section',
151 'http://other.example/next',
152 ' \tHt\nTpS://other.example/next',
153 '/next#same',
154 '/current?query=2#same',
155 '/current?query=1',
156 ])('exempts only the first unload for %j', async (href) => {
157 const {
158 router,
159 assign,
160 replace: replaceLocation,
161 dispatchBeforeUnload,
162 } = setupDocumentNavigation()
163​
164 await router.navigate({ href, reloadDocument: true, replace })
165​
166 expect(assign).toHaveBeenCalledWith(href)
167 expect(replaceLocation).toHaveBeenCalledTimes(replace ? 1 : 0)
168 expect(dispatchBeforeUnload()).toBe(false)
169 expect(dispatchBeforeUnload()).toBe(true)
170 })
171​
172 it('resolves relative fragments against the document base', async () => {
173 const { router, dispatchBeforeUnload } = setupDocumentNavigation({
174 baseHref: '/different-document',
175 })
176​
177 await router.navigate({ href: '#same', reloadDocument: true, replace })
178​
179 expect(dispatchBeforeUnload()).toBe(false)
180 expect(dispatchBeforeUnload()).toBe(true)
181 })
182​
183 it('preserves the next unload warning when an external handler skips blockers', async () => {
184 const { router, blockerFn, dispatchBeforeUnload } =
185 setupDocumentNavigation()
186​
187 await router.navigate({
188 href: 'mailto:user@example.com',
189 ignoreBlocker: true,
190 replace,
191 })
192​
193 expect(blockerFn).not.toHaveBeenCalled()
194 expect(dispatchBeforeUnload()).toBe(true)
195 })
196​
197 it.each(['https://[', 'mailto:user@example.com', '#same'])(
198 'clears a previously prepared exemption before attempting %j',
199 async (href) => {
200 const { router, dispatchBeforeUnload } = setupDocumentNavigation()
201 await router.navigate({ href: 'https://other.example/next' })
202​
203 const navigation = router.navigate({
204 href,
205 reloadDocument: true,
206 replace,
207 })
208 if (href === 'https://[') {
209 await expect(navigation).rejects.toThrow()
210 } else {
211 await navigation
212 }
213​
214 expect(dispatchBeforeUnload()).toBe(true)
215 },
216 )
217 },