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

cache-commit.test.ts

255 lines7.9 KB

1import { describe, expect, test, vi } from 'vitest'
2import { createMemoryHistory } from '@tanstack/history'
3import { BaseRootRoute, BaseRoute } from '../src'
4import { commitMatches } from '../src/load-client'
5import { createTestRouter } from './routerTestUtils'
6import type { AnyRouteMatch, AnyRouter } from '../src'
7import type { LoaderFlight, LoadTransaction } from '../src/load-client'
8​
9type Match = AnyRouteMatch & { _flight?: LoaderFlight }
10​
11function resource(leases = 1): LoaderFlight {
12 return [Promise.resolve([0, undefined]), new AbortController(), leases]
14​
15function match(id: string, flight?: LoaderFlight): Match {
16 return {
17 id,
18 routeId: '/items/$id',
19 status: 'success',
20 updatedAt: 0,
21 _flight: flight,
22 } as Match
24​
25function setup(
26 previous: Array<Match>,
27 cached: Array<Match>,
28 next = [match('next')],
29) {
30 const tx = [
31 new AbortController(),
32 0,
33 undefined,
34 next,
35 0,
36 Promise.resolve(),
37 ] as unknown as LoadTransaction
38 const publish = vi.fn()
39 const router = {
40 _tx: tx,
41 _committed: previous,
42 _cache: new Map(cached.map((entry) => [entry.id, entry])),
43 _flights: new Map(
44 [...previous, ...cached, ...next]
45 .filter((entry) => entry._flight)
46 .map((entry) => [entry.id, entry._flight!]),
47 ),
48 options: {},
49 routesById: {
50 '/items/$id': {
51 options: {
52 loader: () => {},
53 gcTime: Infinity,
54 preloadGcTime: Infinity,
55 },
56 },
57 },
58 stores: { setMatches: publish },
59 } as unknown as AnyRouter
60 return {
61 router,
62 publish,
63 tx,
64 next,
65 commit: () => commitMatches(router, tx, next),
66 }
68​
69describe('commit cache ownership', () => {
70 test.each(['error', 'notFound', 'pending', 'global not found'] as const)(
71 'only supersedes the rendered prefix and settled descendants at a %s boundary',
72 (boundaryKind) => {
73 const cached = [
74 'prefix',
75 'boundary',
76 'settled',
77 'pending',
78 'failed',
79 'unrelated',
80 ].map((id) => match(id, resource()))
81 const next = cached.slice(0, -1).map((entry) => match(entry.id))
82 if (boundaryKind === 'global not found') {
83 next[1]!._notFound = true
84 } else {
85 next[1]!.status = boundaryKind
86 }
87 next[3]!.status = 'pending'
88 next[4]!.status = 'error'
89 const { router, commit } = setup([], cached, next)
90​
91 commit()
92​
93 expect([...router._cache.keys()]).toEqual([
94 'pending',
95 'failed',
96 'unrelated',
97 ])
98 for (const [index, entry] of cached.entries()) {
99 if (index < 3) {
100 expect(entry._flight).toBeUndefined()
101 } else {
102 expect(router._cache.get(entry.id)).toBe(entry)
103 expect(entry._flight?.[1].signal.aborted).toBe(false)
104 }
105 }
106 },
107 )
108​
109 test('retains cached identities and releases the committed owner cloned into cache', () => {
110 const retainedFlight = resource()
111 const departedFlight = resource()
112 const retained = match('retained', retainedFlight)
113 const departed = match('departed', departedFlight)
114 const { router, commit } = setup([departed], [retained])
115​
116 commit()
117​
118 expect(router._cache.get('retained')).toBe(retained)
119 expect(retained._flight).toBe(retainedFlight)
120 expect(retainedFlight[2]).toBe(1)
121 expect(retainedFlight[1].signal.aborted).toBe(false)
122 expect(router._cache.get('departed')).not.toBe(departed)
123 expect((router._cache.get('departed') as Match)._flight).toBeUndefined()
124 expect(departed._flight).toBeUndefined()
125 expect(departedFlight[1].signal.aborted).toBe(true)
126 })
127​
128 test('keeps a retained generation alive when a departing generation shares its flight', () => {
129 const shared = resource(2)
130 const departed = match('same', shared)
131 const retained = match('same', shared)
132 const { router, commit } = setup([departed], [retained])
133​
134 commit()
135​
136 expect(router._cache.get('same')).toBe(retained)
137 expect(departed._flight).toBeUndefined()
138 expect(retained._flight).toBe(shared)
139 expect(shared[2]).toBe(1)
140 expect(shared[1].signal.aborted).toBe(false)
141 })
142​
143 test('releases the old same-id generation without releasing its replacement', () => {
144 const oldFlight = resource()
145 const newFlight = resource()
146 const old = match('same', oldFlight)
147 const replacement = match('same', newFlight)
148 const { router, commit } = setup([], [old], [replacement])
149​
150 commit()
151​
152 expect(router._cache.has('same')).toBe(false)
153 expect(old._flight).toBeUndefined()
154 expect(oldFlight[1].signal.aborted).toBe(true)
155 expect(replacement._flight).toBe(newFlight)
156 expect(newFlight[1].signal.aborted).toBe(false)
157 expect(router._flights?.get('same')).toBe(newFlight)
158 })
159​
160 test('detaches all expired owners before abort listeners run, including duplicate objects', () => {
161 const shared = resource(2)
162 const first = match('first', shared)
163 const second = match('second', shared)
164 first.status = second.status = 'error'
165 const { router, tx, next, commit } = setup([first], [first, second])
166 const onAbort = vi.fn(() => {
167 expect(first._flight).toBeUndefined()
168 expect(second._flight).toBeUndefined()
169 expect(router._cache.size).toBe(0)
170 expect(router._committed).toBe(next)
171 expect(tx[3]).toEqual([])
172 })
173 shared[1].signal.addEventListener('abort', onAbort)
174​
175 commit()
176​
177 expect(shared[2]).toBe(0)
178 expect(onAbort).toHaveBeenCalledOnce()
179 })
180​
181 test('uses cache contents after synchronous publication mutation', () => {
182 const retainedFlight = resource()
183 const retained = match('retained', retainedFlight)
184 const { router, publish, commit } = setup([], [retained])
185 publish.mockImplementation(() => router._cache.delete('retained'))
186​
187 commit()
188​
189 expect(retained._flight).toBeUndefined()
190 expect(retainedFlight[1].signal.aborted).toBe(true)
191 })
192​
193 test('uses the captured cache if publication replaces the router cache', () => {
194 const retainedFlight = resource()
195 const retained = match('retained', retainedFlight)
196 const { router, publish, commit } = setup([], [retained])
197 publish.mockImplementation(() => {
198 router._cache = new Map()
199 })
200​
201 commit()
202​
203 expect(router._cache.size).toBe(0)
204 expect(retained._flight).toBe(retainedFlight)
205 expect(retainedFlight[1].signal.aborted).toBe(false)
206 })
207})
208​
209test('an unrelated navigation retains a fresh preload flight and evicts an expired one', async () => {
210 let freshSignal: AbortSignal | undefined
211 let expiredSignal: AbortSignal | undefined
212 const root = new BaseRootRoute({})
213 const home = new BaseRoute({ getParentRoute: () => root, path: '/' })
214 const other = new BaseRoute({ getParentRoute: () => root, path: '/other' })
215 const freshLoader = vi.fn(
216 ({ abortController }: { abortController: AbortController }) => {
217 freshSignal = abortController.signal
218 return 'fresh data'
219 },
220 )
221 const fresh = new BaseRoute({
222 getParentRoute: () => root,
223 path: '/fresh',
224 loader: freshLoader,
225 staleTime: Infinity,
226 preloadStaleTime: Infinity,
227 preloadGcTime: Infinity,
228 })
229 const expired = new BaseRoute({
230 getParentRoute: () => root,
231 path: '/expired',
232 loader: ({ abortController }) => {
233 expiredSignal = abortController.signal
234 return 'expired data'
235 },
236 preloadGcTime: 0,
237 })
238 const router = createTestRouter({
239 routeTree: root.addChildren([home, other, fresh, expired]),
240 history: createMemoryHistory({ initialEntries: ['/'] }),
241 })
242 await router.load()
243 await router.preloadRoute({ to: '/fresh' })
244 await router.preloadRoute({ to: '/expired' })
245 expect(freshSignal?.aborted).toBe(false)
246 expect(expiredSignal?.aborted).toBe(false)
247​
248 await router.navigate({ to: '/other' })
249​
250 expect(freshSignal?.aborted).toBe(false)
251 expect(expiredSignal?.aborted).toBe(true)
252 await router.navigate({ to: '/fresh' })
253 expect(freshLoader).toHaveBeenCalledOnce()
254 expect(router.state.matches.at(-1)?.loaderData).toBe('fresh data')
255})