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

BroadcastQueryClientProvider.test.tsx

329 lines8.8 KB

1import { act, render } from '@testing-library/react'
2import {
3 IsRestoringProvider,
4 QueryClient,
5 useQuery,
6} from '@tanstack/react-query'
7import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
8import { BroadcastQueryClientProvider } from '../BroadcastQueryClientProvider'
9​
10const mockState = vi.hoisted(() => {
11 const state: {
12 resolveRestore?: () => void
13 restoreResolvers: Array<() => void>
14 } = { restoreResolvers: [] }
15 const cleanup = vi.fn()
16 const restore = vi.fn(() => {
17 const restorePromise = new Promise<void>((resolve) => {
18 state.restoreResolvers.push(resolve)
19 state.resolveRestore = resolve
20 })
21 return [cleanup, restorePromise] as const
22 })
23 return { cleanup, restore, state }
24})
25​
26vi.mock('@tanstack/query-broadcast-client-experimental', () => ({
27 broadcastQueryClientRestore: mockState.restore,
28}))
29​
30describe('BroadcastQueryClientProvider', () => {
31 beforeEach(() => {
32 vi.useFakeTimers()
33 mockState.cleanup.mockReset()
34 mockState.restore.mockClear()
35 mockState.state.resolveRestore = undefined
36 mockState.state.restoreResolvers.length = 0
37 })
38​
39 afterEach(() => {
40 vi.useRealTimers()
41 })
42​
43 it('prevents a fresh query from fetching before bootstrap completes', async () => {
44 const queryKey = ['bootstrap-provider']
45 const queryFn = vi.fn().mockResolvedValue('from-network')
46 const queryClient = new QueryClient()
47 queryClient.setQueryData(queryKey, 'from-cache', {
48 updatedAt: Date.now(),
49 })
50​
51 function Page() {
52 const query = useQuery({
53 queryKey,
54 queryFn,
55 staleTime: Infinity,
56 })
57​
58 return <div>{query.data ?? query.fetchStatus}</div>
59 }
60​
61 const rendered = render(
62 <BroadcastQueryClientProvider
63 client={queryClient}
64 broadcastOptions={{ broadcastChannel: 'test-channel' }}
65 >
66 <Page />
67 </BroadcastQueryClientProvider>,
68 )
69​
70 expect(rendered.getByText('from-cache')).toBeInTheDocument()
71 expect(queryFn).not.toHaveBeenCalled()
72 expect(mockState.restore).toHaveBeenCalledWith({
73 broadcastChannel: 'test-channel',
74 queryClient,
75 })
76​
77 await act(() => {
78 mockState.state.resolveRestore?.()
79 })
80​
81 expect(rendered.getByText('from-cache')).toBeInTheDocument()
82 expect(queryFn).not.toHaveBeenCalled()
83​
84 rendered.unmount()
85 expect(mockState.cleanup).toHaveBeenCalledOnce()
86 })
87​
88 it('allows a stale query to refetch after bootstrap completes', async () => {
89 const queryKey = ['stale-bootstrap-provider']
90 const queryFn = vi.fn().mockResolvedValue('fresh-data')
91 const queryClient = new QueryClient()
92 queryClient.setQueryData(queryKey, 'stale-cache', { updatedAt: 0 })
93​
94 function Page() {
95 const query = useQuery({
96 queryKey,
97 queryFn,
98 staleTime: 0,
99 })
100​
101 return <div>{query.data ?? query.fetchStatus}</div>
102 }
103​
104 const rendered = render(
105 <BroadcastQueryClientProvider
106 client={queryClient}
107 broadcastOptions={{ broadcastChannel: 'test-channel' }}
108 >
109 <Page />
110 </BroadcastQueryClientProvider>,
111 )
112​
113 expect(queryFn).not.toHaveBeenCalled()
114​
115 await act(() => {
116 mockState.state.resolveRestore?.()
117 })
118​
119 await act(async () => {
120 await Promise.resolve()
121 })
122 expect(queryFn).toHaveBeenCalledOnce()
123 rendered.unmount()
124 })
125​
126 it('preserves a parent restore gate after local bootstrap completes', async () => {
127 const queryFn = vi.fn().mockResolvedValue('network')
128 const queryClient = new QueryClient()
129​
130 function Page() {
131 const query = useQuery({
132 queryKey: ['parent-restore-gate'],
133 queryFn,
134 })
135 return <div>{query.fetchStatus}</div>
136 }
137​
138 const rendered = render(
139 <IsRestoringProvider value={true}>
140 <BroadcastQueryClientProvider
141 client={queryClient}
142 broadcastOptions={{ broadcastChannel: 'test-channel' }}
143 >
144 <Page />
145 </BroadcastQueryClientProvider>
146 </IsRestoringProvider>,
147 )
148​
149 await act(() => {
150 mockState.state.resolveRestore?.()
151 })
152​
153 expect(queryFn).not.toHaveBeenCalled()
154 rendered.unmount()
155 })
156​
157 it('allows an empty query to fetch after bootstrap completes', async () => {
158 const queryFn = vi.fn().mockResolvedValue('network')
159 const queryClient = new QueryClient()
160​
161 function Page() {
162 const query = useQuery({
163 queryKey: ['empty-bootstrap'],
164 queryFn,
165 })
166 return <div>{query.fetchStatus}</div>
167 }
168​
169 const rendered = render(
170 <BroadcastQueryClientProvider
171 client={queryClient}
172 broadcastOptions={{ broadcastChannel: 'test-channel' }}
173 >
174 <Page />
175 </BroadcastQueryClientProvider>,
176 )
177​
178 expect(queryFn).not.toHaveBeenCalled()
179 await act(() => {
180 mockState.state.resolveRestore?.()
181 })
182 await act(async () => {
183 await Promise.resolve()
184 })
185​
186 expect(queryFn).toHaveBeenCalledOnce()
187 rendered.unmount()
188 })
189​
190 it('gates a replacement QueryClient before its restore effect runs', async () => {
191 const queryKey = ['replacement-client-bootstrap']
192 const queryFn = vi.fn().mockResolvedValue('network')
193 const firstClient = new QueryClient()
194 const replacementClient = new QueryClient()
195 firstClient.setQueryData(queryKey, 'first-cache', {
196 updatedAt: Date.now(),
197 })
198​
199 function Page() {
200 const query = useQuery({ queryKey, queryFn, staleTime: Infinity })
201 return <div>{query.data ?? query.fetchStatus}</div>
202 }
203​
204 const rendered = render(
205 <BroadcastQueryClientProvider
206 client={firstClient}
207 broadcastOptions={{ broadcastChannel: 'test-channel' }}
208 >
209 <Page key="first" />
210 </BroadcastQueryClientProvider>,
211 )
212​
213 await act(() => {
214 mockState.state.resolveRestore?.()
215 })
216​
217 rendered.rerender(
218 <BroadcastQueryClientProvider
219 client={replacementClient}
220 broadcastOptions={{ broadcastChannel: 'test-channel' }}
221 >
222 <Page key="replacement" />
223 </BroadcastQueryClientProvider>,
224 )
225​
226 expect(queryFn).not.toHaveBeenCalled()
227 expect(mockState.restore).toHaveBeenCalledTimes(2)
228 expect(mockState.cleanup).toHaveBeenCalledOnce()
229​
230 await act(() => {
231 mockState.state.resolveRestore?.()
232 })
233 await act(async () => {
234 await Promise.resolve()
235 })
236​
237 expect(queryFn).toHaveBeenCalledOnce()
238 rendered.unmount()
239 expect(mockState.cleanup).toHaveBeenCalledTimes(2)
240 })
241​
242 it('does not let old restore promises open a rapidly replaced client gate', async () => {
243 const queryFn = vi.fn().mockResolvedValue('network')
244 const firstClient = new QueryClient()
245 const replacementClient = new QueryClient()
246 const finalClient = new QueryClient()
247​
248 function Page() {
249 const query = useQuery({
250 queryKey: ['stale-restore-promise'],
251 queryFn,
252 })
253 return <div>{query.fetchStatus}</div>
254 }
255​
256 const rendered = render(
257 <BroadcastQueryClientProvider
258 client={firstClient}
259 broadcastOptions={{ broadcastChannel: 'test-channel' }}
260 >
261 <Page key="first" />
262 </BroadcastQueryClientProvider>,
263 )
264​
265 rendered.rerender(
266 <BroadcastQueryClientProvider
267 client={replacementClient}
268 broadcastOptions={{ broadcastChannel: 'test-channel' }}
269 >
270 <Page key="replacement" />
271 </BroadcastQueryClientProvider>,
272 )
273​
274 rendered.rerender(
275 <BroadcastQueryClientProvider
276 client={finalClient}
277 broadcastOptions={{ broadcastChannel: 'test-channel' }}
278 >
279 <Page key="final" />
280 </BroadcastQueryClientProvider>,
281 )
282​
283 const firstRestore = mockState.state.restoreResolvers[0]
284 const replacementRestore = mockState.state.restoreResolvers[1]
285 const finalRestore = mockState.state.restoreResolvers[2]
286 expect(firstRestore).toEqual(expect.any(Function))
287 expect(replacementRestore).toEqual(expect.any(Function))
288 expect(finalRestore).toEqual(expect.any(Function))
289​
290 await act(async () => {
291 firstRestore?.()
292 await Promise.resolve()
293 })
294 expect(queryFn).not.toHaveBeenCalled()
295​
296 await act(async () => {
297 replacementRestore?.()
298 await Promise.resolve()
299 })
300 expect(queryFn).not.toHaveBeenCalled()
301​
302 await act(async () => {
303 finalRestore?.()
304 await Promise.resolve()
305 })
306 expect(queryFn).toHaveBeenCalledOnce()
307 rendered.unmount()
308 })
309​
310 it('does not restart restore when the QueryClient is unchanged', () => {
311 const queryClient = new QueryClient()
312 const rendered = render(
313 <BroadcastQueryClientProvider
314 client={queryClient}
315 broadcastOptions={{ broadcastChannel: 'test-channel' }}
316 />,
317 )
318​
319 rendered.rerender(
320 <BroadcastQueryClientProvider
321 client={queryClient}
322 broadcastOptions={{ broadcastChannel: 'test-channel' }}
323 />,
324 )
325​
326 expect(mockState.restore).toHaveBeenCalledOnce()
327 rendered.unmount()
328 })
329})