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

index.test.ts

352 lines10.4 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​
88 expect(mockPostMessage).toHaveBeenCalled()
89 })
90​
91 it('should keep broadcasting local changes after query.setState throws for an existing query', () => {
92 const existingKey = queryKey()
93 const localKey = queryKey()
94​
95 broadcastQueryClient({
96 queryClient,
97 broadcastChannel: 'test_channel',
98 })
99​
100 // Populate the cache with an existing query so the incoming message
101 // below is applied via `query.setState` rather than `queryCache.build`.
102 queryClient.setQueryData(existingKey, { value: 0 })
103 const existingQuery = queryCache.find({ queryKey: existingKey })!
104​
105 const explodingUnsubscribe = queryCache.subscribe(() => {
106 throw new Error('boom from an unrelated cache listener')
107 })
108​
109 expect(() => {
110 lastCreatedChannel.onmessage?.({
111 type: 'updated',
112 queryHash: existingQuery.queryHash,
113 queryKey: existingKey,
114 state: { data: 2 },
115 })
116 }).toThrow('boom')
117​
118 explodingUnsubscribe()
119 mockPostMessage.mockClear()
120​
121 queryClient.setQueryData(localKey, { value: 1 })
122​
123 expect(mockPostMessage).toHaveBeenCalled()
124 })
125 })
126​
127 describe('postMessage error handling', () => {
128 let originalEnv: string | undefined
129​
130 beforeEach(() => {
131 originalEnv = process.env['NODE_ENV']
132 })
133​
134 afterEach(() => {
135 process.env['NODE_ENV'] = originalEnv
136 })
137​
138 it('should not cause an unhandled rejection when onBroadcastError itself throws', async () => {
139 const key = queryKey()
140 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
141 mockPostMessage.mockRejectedValueOnce(cloneError)
142​
143 const unhandledRejections: Array<unknown> = []
144 const onUnhandledRejection = (reason: unknown) => {
145 unhandledRejections.push(reason)
146 }
147 process.on('unhandledRejection', onUnhandledRejection)
148​
149 try {
150 const onBroadcastError = vi.fn().mockImplementation(() => {
151 throw new Error('boom')
152 })
153​
154 broadcastQueryClient({
155 queryClient,
156 broadcastChannel: 'test_channel',
157 onBroadcastError,
158 })
159​
160 queryClient.setQueryData(key, { value: 1 })
161​
162 await sleep(0)
163​
164 expect(onBroadcastError).toHaveBeenCalledWith(
165 cloneError,
166 expect.objectContaining<BroadcastErrorEvent>({
167 type: 'added',
168 queryHash: expect.any(String) as string,
169 queryKey: key,
170 }),
171 )
172 expect(unhandledRejections).toHaveLength(0)
173 } finally {
174 process.off('unhandledRejection', onUnhandledRejection)
175 }
176 })
177​
178 it('should warn in dev when onBroadcastError itself throws', async () => {
179 const key = queryKey()
180 process.env['NODE_ENV'] = 'development'
181 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
182 const callbackError = new Error('boom')
183 mockPostMessage.mockRejectedValueOnce(cloneError)
184​
185 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
186​
187 try {
188 broadcastQueryClient({
189 queryClient,
190 broadcastChannel: 'test_channel',
191 onBroadcastError: () => {
192 throw callbackError
193 },
194 })
195​
196 queryClient.setQueryData(key, { value: 1 })
197​
198 await sleep(0)
199​
200 expect(warnSpy).toHaveBeenCalledWith(
201 expect.stringContaining('onBroadcastError threw while handling'),
202 callbackError,
203 )
204 } finally {
205 warnSpy.mockRestore()
206 }
207 })
208​
209 it('should not cause an unhandled rejection when async onBroadcastError rejects', async () => {
210 const key = queryKey()
211 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
212 mockPostMessage.mockRejectedValueOnce(cloneError)
213​
214 const unhandledRejections: Array<unknown> = []
215 const onUnhandledRejection = (reason: unknown) => {
216 unhandledRejections.push(reason)
217 }
218 process.on('unhandledRejection', onUnhandledRejection)
219​
220 try {
221 const onBroadcastError = vi
222 .fn()
223 .mockRejectedValueOnce(new Error('async boom'))
224​
225 broadcastQueryClient({
226 queryClient,
227 broadcastChannel: 'test_channel',
228 onBroadcastError,
229 })
230​
231 queryClient.setQueryData(key, { value: 1 })
232​
233 await sleep(10)
234​
235 expect(onBroadcastError).toHaveBeenCalledWith(
236 cloneError,
237 expect.objectContaining<BroadcastErrorEvent>({
238 type: 'added',
239 queryHash: expect.any(String) as string,
240 queryKey: key,
241 }),
242 )
243 expect(unhandledRejections).toHaveLength(0)
244 } finally {
245 process.off('unhandledRejection', onUnhandledRejection)
246 }
247 })
248​
249 it('should warn in dev when async onBroadcastError rejects', async () => {
250 const key = queryKey()
251 process.env['NODE_ENV'] = 'development'
252 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
253 const asyncError = new Error('async boom')
254 mockPostMessage.mockRejectedValueOnce(cloneError)
255​
256 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
257​
258 try {
259 broadcastQueryClient({
260 queryClient,
261 broadcastChannel: 'test_channel',
262 onBroadcastError: () => Promise.reject(asyncError),
263 })
264​
265 queryClient.setQueryData(key, { value: 1 })
266​
267 await sleep(10)
268​
269 expect(warnSpy).toHaveBeenCalledWith(
270 expect.stringContaining('onBroadcastError threw while handling'),
271 asyncError,
272 )
273 } finally {
274 warnSpy.mockRestore()
275 }
276 })
277​
278 it('should call onBroadcastError when postMessage fails', async () => {
279 const key = queryKey()
280 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
281 mockPostMessage.mockRejectedValueOnce(cloneError)
282​
283 const onBroadcastError = vi.fn()
284 broadcastQueryClient({
285 queryClient,
286 broadcastChannel: 'test_channel',
287 onBroadcastError,
288 })
289​
290 queryClient.setQueryData(key, { value: 1 })
291​
292 await sleep(0)
293 expect(onBroadcastError).toHaveBeenCalledWith(
294 cloneError,
295 expect.objectContaining<BroadcastErrorEvent>({
296 type: 'added',
297 queryHash: expect.any(String) as string,
298 queryKey: key,
299 }),
300 )
301 })
302​
303 it('should warn in dev when postMessage fails and onBroadcastError is not provided', async () => {
304 const key = queryKey()
305 process.env['NODE_ENV'] = 'development'
306 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
307 mockPostMessage.mockRejectedValueOnce(cloneError)
308​
309 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
310​
311 try {
312 broadcastQueryClient({
313 queryClient,
314 broadcastChannel: 'test_channel',
315 })
316​
317 queryClient.setQueryData(key, { value: 1 })
318​
319 await sleep(0)
320 expect(warnSpy).toHaveBeenCalledWith(
321 expect.stringContaining('cross-tab sync for this query was skipped'),
322 cloneError,
323 )
324 } finally {
325 warnSpy.mockRestore()
326 }
327 })
328​
329 it('should not warn in production when postMessage fails', async () => {
330 const key = queryKey()
331 process.env['NODE_ENV'] = 'production'
332 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
333 mockPostMessage.mockRejectedValueOnce(cloneError)
334​
335 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
336​
337 try {
338 broadcastQueryClient({
339 queryClient,
340 broadcastChannel: 'test_channel',
341 })
342​
343 queryClient.setQueryData(key, { value: 1 })
344​
345 await sleep(0)
346 expect(warnSpy).not.toHaveBeenCalled()
347 } finally {
348 warnSpy.mockRestore()
349 }
350 })
351 })
352})