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

index.test.ts

402 lines12.5 KB

1import { QueryClient } from '@tanstack/query-core'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import { queryKey, sleep } from '@tanstack/query-test-utils'
4import { broadcastQueryClient } from '..'
5import type { BroadcastErrorEvent } from '..'
6import type { QueryCache } from '@tanstack/query-core'
7​
8const mockPostMessage = vi.fn().mockResolvedValue(undefined)
9const mockClose = vi.fn()
10let lastCreatedChannel: { onmessage: ((action: any) => void) | null }
11​
12vi.mock('broadcast-channel', async (importOriginal) => {
13 const actual = await importOriginal()
14 return {
15 ...(actual as object),
16 BroadcastChannel: class MockBroadcastChannel {
17 onmessage = null
18 postMessage = mockPostMessage
19 close = mockClose
20 constructor() {
21 lastCreatedChannel = this
22 }
23 },
24 }
25})
26​
27describe('broadcastQueryClient', () => {
28 let queryClient: QueryClient
29 let queryCache: QueryCache
30​
31 beforeEach(() => {
32 queryClient = new QueryClient()
33 queryCache = queryClient.getQueryCache()
34 mockPostMessage.mockResolvedValue(undefined)
35 mockClose.mockReset()
36 })
37​
38 it('should subscribe to the query cache', () => {
39 broadcastQueryClient({
40 queryClient,
41 broadcastChannel: 'test_channel',
42 })
43 expect(queryCache.hasListeners()).toBe(true)
44 })
45​
46 it('should not have any listeners after cleanup', () => {
47 const unsubscribe = broadcastQueryClient({
48 queryClient,
49 broadcastChannel: 'test_channel',
50 })
51 unsubscribe()
52 expect(queryCache.hasListeners()).toBe(false)
53 })
54​
55 describe('incoming message handling', () => {
56 it('should keep broadcasting local changes after applying an incoming message throws', () => {
57 const remoteKey = queryKey()
58 const localKey = queryKey()
59​
60 broadcastQueryClient({
61 queryClient,
62 broadcastChannel: 'test_channel',
63 })
64​
65 // Simulate some other part of the app (e.g. another cache subscriber)
66 // throwing synchronously while an incoming cross-tab message is being
67 // applied locally.
68 const explodingUnsubscribe = queryCache.subscribe(() => {
69 throw new Error('boom from an unrelated cache listener')
70 })
71​
72 expect(() => {
73 lastCreatedChannel.onmessage?.({
74 type: 'added',
75 queryHash: JSON.stringify(remoteKey),
76 queryKey: remoteKey,
77 state: { data: 1 },
78 })
79 }).toThrow('boom')
80​
81 explodingUnsubscribe()
82 mockPostMessage.mockClear()
83​
84 // A later local change must still be broadcast to other tabs, instead
85 // of being silently swallowed because the transaction flag got stuck.
86 queryClient.setQueryData(localKey, { value: 1 })
87 expect(mockPostMessage).toHaveBeenCalled()
88 })
89​
90 it('should keep broadcasting local changes after query.setState throws for an existing query', () => {
91 const existingKey = queryKey()
92 const localKey = queryKey()
93​
94 broadcastQueryClient({
95 queryClient,
96 broadcastChannel: 'test_channel',
97 })
98​
99 // Populate the cache with an existing query so the incoming message
100 // below is applied via `query.setState` rather than `queryCache.build`.
101 queryClient.setQueryData(existingKey, { value: 0 })
102 const existingQuery = queryCache.find({ queryKey: existingKey })!
103​
104 const explodingUnsubscribe = queryCache.subscribe(() => {
105 throw new Error('boom from an unrelated cache listener')
106 })
107​
108 expect(() => {
109 lastCreatedChannel.onmessage?.({
110 type: 'updated',
111 queryHash: existingQuery.queryHash,
112 queryKey: existingKey,
113 state: { data: 2 },
114 })
115 }).toThrow('boom')
116​
117 explodingUnsubscribe()
118 mockPostMessage.mockClear()
119​
120 queryClient.setQueryData(localKey, { value: 1 })
121 expect(mockPostMessage).toHaveBeenCalled()
122 })
123​
124 it('should not overwrite an existing query with data when an "added" message arrives for it', () => {
125 const existingKey = queryKey()
126​
127 broadcastQueryClient({
128 queryClient,
129 broadcastChannel: 'test_channel',
130 })
131​
132 // A query that already resolved in this tab (e.g. it fetched before
133 // another tab mounted the same key).
134 queryClient.setQueryData(existingKey, { value: 'resolved' })
135 const existingQuery = queryCache.find({ queryKey: existingKey })!
136​
137 // Another tab just mounted the same key for the first time, so its
138 // `build()` broadcasts an `added` message with a pending state and
139 // no data.
140 lastCreatedChannel.onmessage?.({
141 type: 'added',
142 queryHash: existingQuery.queryHash,
143 queryKey: existingKey,
144 state: { status: 'pending', data: undefined },
145 })
146 expect(queryClient.getQueryData(existingKey)).toEqual({
147 value: 'resolved',
148 })
149 expect(queryClient.getQueryState(existingKey)?.status).toBe('success')
150 })
151​
152 it('should adopt an "added" message\'s state for an existing query that has no data yet', () => {
153 const existingKey = queryKey()
154​
155 broadcastQueryClient({
156 queryClient,
157 broadcastChannel: 'test_channel',
158 })
159​
160 // This tab has already built the query (e.g. an observer mounted it)
161 // but hasn't fetched it yet.
162 const existingQuery = queryCache.build(queryClient, {
163 queryKey: existingKey,
164 })
165​
166 // Another tab already had this key resolved (e.g. via `initialData`)
167 // when it mounted, so its `added` message carries real data.
168 lastCreatedChannel.onmessage?.({
169 type: 'added',
170 queryHash: existingQuery.queryHash,
171 queryKey: existingKey,
172 state: { status: 'success', data: { value: 'from other tab' } },
173 })
174 expect(queryClient.getQueryData(existingKey)).toEqual({
175 value: 'from other tab',
176 })
177 })
178 })
179​
180 describe('postMessage error handling', () => {
181 let originalEnv: string | undefined
182​
183 beforeEach(() => {
184 originalEnv = process.env['NODE_ENV']
185 })
186​
187 afterEach(() => {
188 process.env['NODE_ENV'] = originalEnv
189 })
190​
191 it('should not cause an unhandled rejection when onBroadcastError itself throws', async () => {
192 const key = queryKey()
193 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
194 mockPostMessage.mockRejectedValueOnce(cloneError)
195​
196 const unhandledRejections: Array<unknown> = []
197 const onUnhandledRejection = (reason: unknown) => {
198 unhandledRejections.push(reason)
199 }
200 process.on('unhandledRejection', onUnhandledRejection)
201​
202 try {
203 const onBroadcastError = vi.fn().mockImplementation(() => {
204 throw new Error('boom')
205 })
206​
207 broadcastQueryClient({
208 queryClient,
209 broadcastChannel: 'test_channel',
210 onBroadcastError,
211 })
212​
213 queryClient.setQueryData(key, { value: 1 })
214 await sleep(0)
215 expect(onBroadcastError).toHaveBeenCalledWith(
216 cloneError,
217 expect.objectContaining<BroadcastErrorEvent>({
218 type: 'added',
219 queryHash: expect.any(String) as string,
220 queryKey: key,
221 }),
222 )
223 expect(unhandledRejections).toHaveLength(0)
224 } finally {
225 process.off('unhandledRejection', onUnhandledRejection)
226 }
227 })
228​
229 it('should warn in dev when onBroadcastError itself throws', async () => {
230 const key = queryKey()
231 process.env['NODE_ENV'] = 'development'
232 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
233 const callbackError = new Error('boom')
234 mockPostMessage.mockRejectedValueOnce(cloneError)
235​
236 const consoleWarnMock = vi
237 .spyOn(console, 'warn')
238 .mockImplementation(() => {})
239​
240 try {
241 broadcastQueryClient({
242 queryClient,
243 broadcastChannel: 'test_channel',
244 onBroadcastError: () => {
245 throw callbackError
246 },
247 })
248​
249 queryClient.setQueryData(key, { value: 1 })
250 await sleep(0)
251 expect(consoleWarnMock).toHaveBeenCalledWith(
252 expect.stringContaining('onBroadcastError threw while handling'),
253 callbackError,
254 )
255 } finally {
256 consoleWarnMock.mockRestore()
257 }
258 })
259​
260 it('should not cause an unhandled rejection when async onBroadcastError rejects', async () => {
261 const key = queryKey()
262 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
263 mockPostMessage.mockRejectedValueOnce(cloneError)
264​
265 const unhandledRejections: Array<unknown> = []
266 const onUnhandledRejection = (reason: unknown) => {
267 unhandledRejections.push(reason)
268 }
269 process.on('unhandledRejection', onUnhandledRejection)
270​
271 try {
272 const onBroadcastError = vi
273 .fn()
274 .mockRejectedValueOnce(new Error('async boom'))
275​
276 broadcastQueryClient({
277 queryClient,
278 broadcastChannel: 'test_channel',
279 onBroadcastError,
280 })
281​
282 queryClient.setQueryData(key, { value: 1 })
283 await sleep(10)
284 expect(onBroadcastError).toHaveBeenCalledWith(
285 cloneError,
286 expect.objectContaining<BroadcastErrorEvent>({
287 type: 'added',
288 queryHash: expect.any(String) as string,
289 queryKey: key,
290 }),
291 )
292 expect(unhandledRejections).toHaveLength(0)
293 } finally {
294 process.off('unhandledRejection', onUnhandledRejection)
295 }
296 })
297​
298 it('should warn in dev when async onBroadcastError rejects', async () => {
299 const key = queryKey()
300 process.env['NODE_ENV'] = 'development'
301 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
302 const asyncError = new Error('async boom')
303 mockPostMessage.mockRejectedValueOnce(cloneError)
304​
305 const consoleWarnMock = vi
306 .spyOn(console, 'warn')
307 .mockImplementation(() => {})
308​
309 try {
310 broadcastQueryClient({
311 queryClient,
312 broadcastChannel: 'test_channel',
313 onBroadcastError: () => Promise.reject(asyncError),
314 })
315​
316 queryClient.setQueryData(key, { value: 1 })
317 await sleep(10)
318 expect(consoleWarnMock).toHaveBeenCalledWith(
319 expect.stringContaining('onBroadcastError threw while handling'),
320 asyncError,
321 )
322 } finally {
323 consoleWarnMock.mockRestore()
324 }
325 })
326​
327 it('should call onBroadcastError when postMessage fails', async () => {
328 const key = queryKey()
329 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
330 mockPostMessage.mockRejectedValueOnce(cloneError)
331​
332 const onBroadcastError = vi.fn()
333 broadcastQueryClient({
334 queryClient,
335 broadcastChannel: 'test_channel',
336 onBroadcastError,
337 })
338​
339 queryClient.setQueryData(key, { value: 1 })
340 await sleep(0)
341 expect(onBroadcastError).toHaveBeenCalledWith(
342 cloneError,
343 expect.objectContaining<BroadcastErrorEvent>({
344 type: 'added',
345 queryHash: expect.any(String) as string,
346 queryKey: key,
347 }),
348 )
349 })
350​
351 it('should warn in dev when postMessage fails and onBroadcastError is not provided', async () => {
352 const key = queryKey()
353 process.env['NODE_ENV'] = 'development'
354 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
355 mockPostMessage.mockRejectedValueOnce(cloneError)
356​
357 const consoleWarnMock = vi
358 .spyOn(console, 'warn')
359 .mockImplementation(() => {})
360​
361 try {
362 broadcastQueryClient({
363 queryClient,
364 broadcastChannel: 'test_channel',
365 })
366​
367 queryClient.setQueryData(key, { value: 1 })
368 await sleep(0)
369 expect(consoleWarnMock).toHaveBeenCalledWith(
370 expect.stringContaining('cross-tab sync for this query was skipped'),
371 cloneError,
372 )
373 } finally {
374 consoleWarnMock.mockRestore()
375 }
376 })
377​
378 it('should not warn in production when postMessage fails', async () => {
379 const key = queryKey()
380 process.env['NODE_ENV'] = 'production'
381 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
382 mockPostMessage.mockRejectedValueOnce(cloneError)
383​
384 const consoleWarnMock = vi
385 .spyOn(console, 'warn')
386 .mockImplementation(() => {})
387​
388 try {
389 broadcastQueryClient({
390 queryClient,
391 broadcastChannel: 'test_channel',
392 })
393​
394 queryClient.setQueryData(key, { value: 1 })
395 await sleep(0)
396 expect(consoleWarnMock).not.toHaveBeenCalled()
397 } finally {
398 consoleWarnMock.mockRestore()
399 }
400 })
401 })
402})