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

cache-replacement.test.ts

105 lines2.8 KB

1import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
2import { TanStackRouterDevtoolsPanelCore } from '../src/TanStackRouterDevtoolsPanelCore'
3import type { AnyRouteMatch, AnyRouter } from '@tanstack/router-core'
4​
5function createCachedMatch(loaderData: string): AnyRouteMatch {
6 return {
7 id: 'cached-match',
8 routeId: '/cached',
9 pathname: '/cached',
10 params: {},
11 search: {},
12 status: 'success',
13 isFetching: false,
14 updatedAt: Date.now(),
15 loaderData,
16 } as AnyRouteMatch
18​
19describe('cached matches', () => {
20 let panel: TanStackRouterDevtoolsPanelCore | undefined
21​
22 // Warm Vite's lazy transform of the panel chunk outside any test so its
23 // cost never counts against a test's timeout budget on slow CI runners.
24 beforeAll(async () => {
25 await import('../src/BaseTanStackRouterDevtoolsPanel')
26 }, 30_000)
27​
28 afterEach(() => {
29 panel?.unmount()
30 panel = undefined
31 document.body.innerHTML = ''
32 try {
33 window.localStorage.clear()
34 } catch {}
35 vi.useRealTimers()
36 })
37​
38 it('uses the default gc time and refreshes replaced cache entries', async () => {
39 vi.useFakeTimers()
40​
41 const route = {
42 id: '/cached',
43 path: 'cached',
44 fullPath: '/cached',
45 rank: 0,
46 children: [],
47 options: { loader: () => undefined },
48 }
49 const routeTree = {
50 id: '__root__',
51 path: '/',
52 fullPath: '/',
53 rank: 0,
54 children: [route],
55 options: {},
56 }
57 const cache = new Map([['cached-match', createCachedMatch('old data')]])
58 const router = {
59 _cache: cache,
60 routeTree,
61 routesById: {
62 __root__: routeTree,
63 '/cached': route,
64 },
65 options: {},
66 navigate: vi.fn(),
67 } as unknown as AnyRouter
68 const routerState = {
69 location: {
70 href: '/',
71 pathname: '/',
72 search: {},
73 searchStr: '',
74 hash: '',
75 },
76 matches: [],
77 }
78 const container = document.createElement('div')
79 document.body.append(container)
80​
81 panel = new TanStackRouterDevtoolsPanelCore({ router, routerState })
82 panel.mount(container)
83​
84 await vi.waitFor(() => {
85 expect(
86 container.querySelector(
87 '[aria-label="Open match details for cached-match"]',
88 ),
89 ).not.toBeNull()
90 })
91 expect(container.textContent).toContain('5min')
92​
93 const cachedMatch = container.querySelector(
94 '[aria-label="Open match details for cached-match"]',
95 ) as HTMLElement
96 cachedMatch.click()
97 expect(container.textContent).toContain('old data')
98​
99 cache.set('cached-match', createCachedMatch('new data'))
100 await vi.advanceTimersByTimeAsync(500)
101​
102 expect(container.textContent).toContain('new data')
103 expect(container.textContent).not.toContain('old data')
104 }, 10_000)
105})