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

index.test.ts

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