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

index.test.ts

268 lines8.0 KB

1import { QueryClient } from '@tanstack/query-core'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import { broadcastQueryClient } from '..'
4import type { BroadcastErrorEvent } from '..'
5import type { QueryCache } from '@tanstack/query-core'
6​
7const mockPostMessage = vi.fn().mockResolvedValue(undefined)
8const mockClose = vi.fn()
9​
10vi.mock('broadcast-channel', async (importOriginal) => {
11 const actual = await importOriginal()
12 return {
13 ...(actual as object),
14 BroadcastChannel: class MockBroadcastChannel {
15 onmessage = null
16 postMessage = mockPostMessage
17 close = mockClose
18 },
19 }
20})
21​
22describe('broadcastQueryClient', () => {
23 let queryClient: QueryClient
24 let queryCache: QueryCache
25​
26 beforeEach(() => {
27 queryClient = new QueryClient()
28 queryCache = queryClient.getQueryCache()
29 mockPostMessage.mockResolvedValue(undefined)
30 mockClose.mockReset()
31 })
32​
33 it('should subscribe to the query cache', () => {
34 broadcastQueryClient({
35 queryClient,
36 broadcastChannel: 'test_channel',
37 })
38 expect(queryCache.hasListeners()).toBe(true)
39 })
40​
41 it('should not have any listeners after cleanup', () => {
42 const unsubscribe = broadcastQueryClient({
43 queryClient,
44 broadcastChannel: 'test_channel',
45 })
46 unsubscribe()
47 expect(queryCache.hasListeners()).toBe(false)
48 })
49​
50 describe('postMessage error handling', () => {
51 let originalEnv: string | undefined
52​
53 beforeEach(() => {
54 originalEnv = process.env['NODE_ENV']
55 })
56​
57 afterEach(() => {
58 process.env['NODE_ENV'] = originalEnv
59 })
60​
61 it('should not cause an unhandled rejection when onBroadcastError itself throws', async () => {
62 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
63 mockPostMessage.mockRejectedValueOnce(cloneError)
64​
65 const unhandledRejections: Array<unknown> = []
66 const onUnhandledRejection = (reason: unknown) => {
67 unhandledRejections.push(reason)
68 }
69 process.on('unhandledRejection', onUnhandledRejection)
70​
71 try {
72 const onBroadcastError = vi.fn().mockImplementation(() => {
73 throw new Error('boom')
74 })
75​
76 broadcastQueryClient({
77 queryClient,
78 broadcastChannel: 'test_channel',
79 onBroadcastError,
80 })
81​
82 queryClient.setQueryData(['test'], { value: 1 })
83​
84 await new Promise((r) => setTimeout(r, 0))
85​
86 expect(onBroadcastError).toHaveBeenCalledWith(
87 cloneError,
88 expect.objectContaining<BroadcastErrorEvent>({
89 type: 'added',
90 queryHash: expect.any(String) as string,
91 queryKey: ['test'],
92 }),
93 )
94 expect(unhandledRejections).toHaveLength(0)
95 } finally {
96 process.off('unhandledRejection', onUnhandledRejection)
97 }
98 })
99​
100 it('should warn in dev when onBroadcastError itself throws', async () => {
101 process.env['NODE_ENV'] = 'development'
102 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
103 const callbackError = new Error('boom')
104 mockPostMessage.mockRejectedValueOnce(cloneError)
105​
106 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
107​
108 try {
109 broadcastQueryClient({
110 queryClient,
111 broadcastChannel: 'test_channel',
112 onBroadcastError: () => {
113 throw callbackError
114 },
115 })
116​
117 queryClient.setQueryData(['test'], { value: 1 })
118​
119 await new Promise((r) => setTimeout(r, 0))
120​
121 expect(warnSpy).toHaveBeenCalledWith(
122 expect.stringContaining('onBroadcastError threw while handling'),
123 callbackError,
124 )
125 } finally {
126 warnSpy.mockRestore()
127 }
128 })
129​
130 it('should not cause an unhandled rejection when async onBroadcastError rejects', async () => {
131 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
132 mockPostMessage.mockRejectedValueOnce(cloneError)
133​
134 const unhandledRejections: Array<unknown> = []
135 const onUnhandledRejection = (reason: unknown) => {
136 unhandledRejections.push(reason)
137 }
138 process.on('unhandledRejection', onUnhandledRejection)
139​
140 try {
141 const onBroadcastError = vi
142 .fn()
143 .mockRejectedValueOnce(new Error('async boom'))
144​
145 broadcastQueryClient({
146 queryClient,
147 broadcastChannel: 'test_channel',
148 onBroadcastError,
149 })
150​
151 queryClient.setQueryData(['test'], { value: 1 })
152​
153 await new Promise((r) => setTimeout(r, 10))
154​
155 expect(onBroadcastError).toHaveBeenCalledWith(
156 cloneError,
157 expect.objectContaining<BroadcastErrorEvent>({
158 type: 'added',
159 queryHash: expect.any(String) as string,
160 queryKey: ['test'],
161 }),
162 )
163 expect(unhandledRejections).toHaveLength(0)
164 } finally {
165 process.off('unhandledRejection', onUnhandledRejection)
166 }
167 })
168​
169 it('should warn in dev when async onBroadcastError rejects', async () => {
170 process.env['NODE_ENV'] = 'development'
171 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
172 const asyncError = new Error('async boom')
173 mockPostMessage.mockRejectedValueOnce(cloneError)
174​
175 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
176​
177 try {
178 broadcastQueryClient({
179 queryClient,
180 broadcastChannel: 'test_channel',
181 onBroadcastError: () => Promise.reject(asyncError),
182 })
183​
184 queryClient.setQueryData(['test'], { value: 1 })
185​
186 await new Promise((r) => setTimeout(r, 10))
187​
188 expect(warnSpy).toHaveBeenCalledWith(
189 expect.stringContaining('onBroadcastError threw while handling'),
190 asyncError,
191 )
192 } finally {
193 warnSpy.mockRestore()
194 }
195 })
196​
197 it('should call onBroadcastError when postMessage fails', async () => {
198 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
199 mockPostMessage.mockRejectedValueOnce(cloneError)
200​
201 const onBroadcastError = vi.fn()
202 broadcastQueryClient({
203 queryClient,
204 broadcastChannel: 'test_channel',
205 onBroadcastError,
206 })
207​
208 queryClient.setQueryData(['test'], { value: 1 })
209​
210 await new Promise((r) => setTimeout(r, 0))
211 expect(onBroadcastError).toHaveBeenCalledWith(
212 cloneError,
213 expect.objectContaining<BroadcastErrorEvent>({
214 type: 'added',
215 queryHash: expect.any(String) as string,
216 queryKey: ['test'],
217 }),
218 )
219 })
220​
221 it('should warn in dev when postMessage fails and onBroadcastError is not provided', async () => {
222 process.env['NODE_ENV'] = 'development'
223 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
224 mockPostMessage.mockRejectedValueOnce(cloneError)
225​
226 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
227​
228 try {
229 broadcastQueryClient({
230 queryClient,
231 broadcastChannel: 'test_channel',
232 })
233​
234 queryClient.setQueryData(['test'], { value: 1 })
235​
236 await new Promise((r) => setTimeout(r, 0))
237 expect(warnSpy).toHaveBeenCalledWith(
238 expect.stringContaining('cross-tab sync for this query was skipped'),
239 cloneError,
240 )
241 } finally {
242 warnSpy.mockRestore()
243 }
244 })
245​
246 it('should not warn in production when postMessage fails', async () => {
247 process.env['NODE_ENV'] = 'production'
248 const cloneError = new DOMException('DataCloneError', 'DataCloneError')
249 mockPostMessage.mockRejectedValueOnce(cloneError)
250​
251 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
252​
253 try {
254 broadcastQueryClient({
255 queryClient,
256 broadcastChannel: 'test_channel',
257 })
258​
259 queryClient.setQueryData(['test'], { value: 1 })
260​
261 await new Promise((r) => setTimeout(r, 0))
262 expect(warnSpy).not.toHaveBeenCalled()
263 } finally {
264 warnSpy.mockRestore()
265 }
266 })
267 })
268})