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

index.test.ts

404 lines12.8 KB

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