Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { queryKey, sleep } from '@tanstack/query-test-utils'
3import { MutationObserver, QueryClient } from '..'
4β
5describe('mutationObserver', () => {
6 let queryClient: QueryClient
7β
8 beforeEach(() => {
9 vi.useFakeTimers()
10 queryClient = new QueryClient()
11 queryClient.mount()
12 })
13β
14 afterEach(() => {
15 queryClient.clear()
16 vi.useRealTimers()
17 })
18β
19 test('onUnsubscribe should not remove the current mutation observer if there is still a subscription', async () => {
20 const mutation = new MutationObserver(queryClient, {
21 mutationFn: (text: string) => sleep(20).then(() => text),
22 })
23β
24 const subscription1Handler = vi.fn()
25 const subscription2Handler = vi.fn()
26β
27 const unsubscribe1 = mutation.subscribe(subscription1Handler)
28 const unsubscribe2 = mutation.subscribe(subscription2Handler)
29β
30 mutation.mutate('input')
31β
32 unsubscribe1()
33β
34 expect(subscription1Handler).toBeCalledTimes(1)
35 expect(subscription2Handler).toBeCalledTimes(1)
36β
37 await vi.advanceTimersByTimeAsync(20)
38 expect(subscription1Handler).toBeCalledTimes(1)
39 expect(subscription2Handler).toBeCalledTimes(2)
40β
41 unsubscribe2()
42 })
43β
44 test('unsubscribe should remove observer to trigger GC', async () => {
45 const mutation = new MutationObserver(queryClient, {
46 mutationFn: (text: string) => sleep(5).then(() => text),
47 gcTime: 10,
48 })
49β
50 const subscriptionHandler = vi.fn()
51β
52 const unsubscribe = mutation.subscribe(subscriptionHandler)
53β
54 mutation.mutate('input')
55β
56 await vi.advanceTimersByTimeAsync(5)
57 expect(queryClient.getMutationCache().findAll()).toHaveLength(1)
58β
59 unsubscribe()
60β
61 await vi.advanceTimersByTimeAsync(10)
62 expect(queryClient.getMutationCache().findAll()).toHaveLength(0)
63 })
64β
65 test('reset should remove observer to trigger GC', async () => {
66 const mutation = new MutationObserver(queryClient, {
67 mutationFn: (text: string) => sleep(5).then(() => text),
68 gcTime: 10,
69 })
70β
71 const subscriptionHandler = vi.fn()
72β
73 const unsubscribe = mutation.subscribe(subscriptionHandler)
74β
75 mutation.mutate('input')
76β
77 await vi.advanceTimersByTimeAsync(5)
78 expect(queryClient.getMutationCache().findAll()).toHaveLength(1)
79β
80 mutation.reset()
81β
82 await vi.advanceTimersByTimeAsync(10)
83 expect(queryClient.getMutationCache().findAll()).toHaveLength(0)
84β
85 unsubscribe()
86 })
87β
88 test('changing mutation keys should reset the observer', async () => {
89 const key = queryKey()
90 const mutation = new MutationObserver(queryClient, {
91 mutationKey: [...key, '1'],
92 mutationFn: (text: string) => sleep(5).then(() => text),
93 })
94β
95 const subscriptionHandler = vi.fn()
96β
97 const unsubscribe = mutation.subscribe(subscriptionHandler)
98β
99 mutation.mutate('input')
100β
101 await vi.advanceTimersByTimeAsync(5)
102 expect(mutation.getCurrentResult()).toMatchObject({
103 status: 'success',
104 data: 'input',
105 })
106β
107 mutation.setOptions({
108 mutationKey: [...key, '2'],
109 })
110β
111 expect(mutation.getCurrentResult()).toMatchObject({
112 status: 'idle',
113 })
114β
115 unsubscribe()
116 })
117β
118 test('changing mutation keys should not affect already existing mutations', async () => {
119 const key = queryKey()
120 const mutationObserver = new MutationObserver(queryClient, {
121 mutationKey: [...key, '1'],
122 mutationFn: (text: string) => sleep(5).then(() => text),
123 })
124β
125 const subscriptionHandler = vi.fn()
126β
127 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
128β
129 mutationObserver.mutate('input')
130β
131 await vi.advanceTimersByTimeAsync(5)
132 expect(
133 queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }),
134 ).toMatchObject({
135 options: { mutationKey: [...key, '1'] },
136 state: {
137 status: 'success',
138 data: 'input',
139 },
140 })
141β
142 mutationObserver.setOptions({
143 mutationKey: [...key, '2'],
144 })
145β
146 expect(
147 queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }),
148 ).toMatchObject({
149 options: { mutationKey: [...key, '1'] },
150 state: {
151 status: 'success',
152 data: 'input',
153 },
154 })
155β
156 unsubscribe()
157 })
158β
159 test('changing mutation meta should not affect successful mutations', async () => {
160 const mutationObserver = new MutationObserver(queryClient, {
161 meta: { a: 1 },
162 mutationFn: (text: string) => sleep(5).then(() => text),
163 })
164β
165 const subscriptionHandler = vi.fn()
166β
167 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
168β
169 mutationObserver.mutate('input')
170β
171 await vi.advanceTimersByTimeAsync(5)
172 expect(queryClient.getMutationCache().find({})).toMatchObject({
173 options: { meta: { a: 1 } },
174 state: {
175 status: 'success',
176 data: 'input',
177 },
178 })
179β
180 mutationObserver.setOptions({
181 meta: { a: 2 },
182 })
183β
184 expect(queryClient.getMutationCache().find({})).toMatchObject({
185 options: { meta: { a: 1 } },
186 state: {
187 status: 'success',
188 data: 'input',
189 },
190 })
191β
192 unsubscribe()
193 })
194β
195 test('mutation cache should have different meta when updated between mutations', async () => {
196 const mutationFn = (text: string) => sleep(5).then(() => text)
197 const mutationObserver = new MutationObserver(queryClient, {
198 meta: { a: 1 },
199 mutationFn,
200 })
201β
202 const subscriptionHandler = vi.fn()
203β
204 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
205β
206 mutationObserver.mutate('input')
207 await vi.advanceTimersByTimeAsync(5)
208β
209 mutationObserver.setOptions({
210 meta: { a: 2 },
211 mutationFn,
212 })
213β
214 mutationObserver.mutate('input')
215 await vi.advanceTimersByTimeAsync(5)
216β
217 const mutations = queryClient.getMutationCache().findAll()
218 expect(mutations[0]).toMatchObject({
219 options: { meta: { a: 1 } },
220 state: {
221 status: 'success',
222 data: 'input',
223 },
224 })
225 expect(mutations[1]).toMatchObject({
226 options: { meta: { a: 2 } },
227 state: {
228 status: 'success',
229 data: 'input',
230 },
231 })
232β
233 unsubscribe()
234 })
235β
236 test('changing mutation meta should not affect rejected mutations', async () => {
237 const mutationObserver = new MutationObserver(queryClient, {
238 meta: { a: 1 },
239 mutationFn: (_: string) =>
240 sleep(5).then(() => Promise.reject(new Error('err'))),
241 })
242β
243 const subscriptionHandler = vi.fn()
244β
245 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
246β
247 mutationObserver.mutate('input').catch(() => undefined)
248β
249 await vi.advanceTimersByTimeAsync(5)
250 expect(queryClient.getMutationCache().find({})).toMatchObject({
251 options: { meta: { a: 1 } },
252 state: {
253 status: 'error',
254 },
255 })
256β
257 mutationObserver.setOptions({
258 meta: { a: 2 },
259 })
260β
261 expect(queryClient.getMutationCache().find({})).toMatchObject({
262 options: { meta: { a: 1 } },
263 state: {
264 status: 'error',
265 },
266 })
267β
268 unsubscribe()
269 })
270β
271 test('changing mutation meta should affect pending mutations', async () => {
272 const mutationObserver = new MutationObserver(queryClient, {
273 meta: { a: 1 },
274 mutationFn: (text: string) => sleep(20).then(() => text),
275 })
276β
277 const subscriptionHandler = vi.fn()
278β
279 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
280β
281 mutationObserver.mutate('input')
282 await vi.advanceTimersByTimeAsync(5)
283 expect(queryClient.getMutationCache().find({})).toMatchObject({
284 options: { meta: { a: 1 } },
285 state: {
286 status: 'pending',
287 },
288 })
289β
290 mutationObserver.setOptions({
291 meta: { a: 2 },
292 })
293β
294 expect(queryClient.getMutationCache().find({})).toMatchObject({
295 options: { meta: { a: 2 } },
296 state: {
297 status: 'pending',
298 },
299 })
300β
301 unsubscribe()
302 })
303β
304 test('mutation callbacks should be called in correct order with correct arguments for success case', async () => {
305 const onSuccess = vi.fn()
306 const onSettled = vi.fn()
307β
308 const mutationObserver = new MutationObserver(queryClient, {
309 mutationFn: (text: string) => Promise.resolve(text.toUpperCase()),
310 })
311β
312 const subscriptionHandler = vi.fn()
313 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
314β
315 mutationObserver.mutate('success', {
316 onSuccess,
317 onSettled,
318 })
319β
320 await vi.advanceTimersByTimeAsync(0)
321β
322 expect(onSuccess).toHaveBeenCalledTimes(1)
323 expect(onSuccess).toHaveBeenCalledWith('SUCCESS', 'success', undefined, {
324 client: queryClient,
325 meta: undefined,
326 mutationKey: undefined,
327 })
328 expect(onSettled).toHaveBeenCalledTimes(1)
329 expect(onSettled).toHaveBeenCalledWith(
330 'SUCCESS',
331 null,
332 'success',
333 undefined,
334 {
335 client: queryClient,
336 meta: undefined,
337 mutationKey: undefined,
338 },
339 )
340β
341 unsubscribe()
342 })
343β
344 test('mutation callbacks should be called in correct order with correct arguments for error case', async () => {
345 const onError = vi.fn()
346 const onSettled = vi.fn()
347β
348 const error = new Error('error')
349 const mutationObserver = new MutationObserver(queryClient, {
350 mutationFn: (_: string) => Promise.reject(error),
351 })
352β
353 const subscriptionHandler = vi.fn()
354 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
355β
356 mutationObserver
357 .mutate('error', {
358 onError,
359 onSettled,
360 })
361 .catch(() => {})
362β
363 await vi.advanceTimersByTimeAsync(0)
364β
365 expect(onError).toHaveBeenCalledTimes(1)
366 expect(onError).toHaveBeenCalledWith(error, 'error', undefined, {
367 client: queryClient,
368 meta: undefined,
369 mutationKey: undefined,
370 })
371 expect(onSettled).toHaveBeenCalledTimes(1)
372 expect(onSettled).toHaveBeenCalledWith(
373 undefined,
374 error,
375 'error',
376 undefined,
377 {
378 client: queryClient,
379 meta: undefined,
380 mutationKey: undefined,
381 },
382 )
383β
384 unsubscribe()
385 })
386β
387 describe('erroneous mutation callback', () => {
388 test('onSuccess and onSettled is transferred to different execution context where it is reported', async ({
389 onTestFinished,
390 }) => {
391 const unhandledRejectionFn = vi.fn()
392 process.on('unhandledRejection', (error) => unhandledRejectionFn(error))
393 onTestFinished(() => {
394 process.off('unhandledRejection', unhandledRejectionFn)
395 })
396β
397 const onSuccessError = new Error('onSuccess-error')
398 const onSuccess = vi.fn(() => {
399 throw onSuccessError
400 })
401 const onSettledError = new Error('onSettled-error')
402 const onSettled = vi.fn(() => {
403 throw onSettledError
404 })
405β
406 const mutationObserver = new MutationObserver(queryClient, {
407 mutationFn: (text: string) => Promise.resolve(text.toUpperCase()),
408 })
409β
410 const subscriptionHandler = vi.fn()
411 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
412β
413 mutationObserver.mutate('success', {
414 onSuccess,
415 onSettled,
416 })
417β
418 await vi.advanceTimersByTimeAsync(0)
419β
420 expect(onSuccess).toHaveBeenCalledTimes(1)
421 expect(onSettled).toHaveBeenCalledTimes(1)
422β
423 expect(unhandledRejectionFn).toHaveBeenCalledTimes(2)
424 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(1, onSuccessError)
425 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(2, onSettledError)
426β
427 expect(subscriptionHandler).toHaveBeenCalledTimes(2)
428β
429 unsubscribe()
430 })
431β
432 test('onError and onSettled is transferred to different execution context where it is reported', async ({
433 onTestFinished,
434 }) => {
435 const unhandledRejectionFn = vi.fn()
436 process.on('unhandledRejection', (error) => unhandledRejectionFn(error))
437 onTestFinished(() => {
438 process.off('unhandledRejection', unhandledRejectionFn)
439 })
440β
441 const onErrorError = new Error('onError-error')
442 const onError = vi.fn(() => {
443 throw onErrorError
444 })
445 const onSettledError = new Error('onSettled-error')
446 const onSettled = vi.fn(() => {
447 throw onSettledError
448 })
449β
450 const error = new Error('error')
451 const mutationObserver = new MutationObserver(queryClient, {
452 mutationFn: (_: string) => Promise.reject(error),
453 })
454β
455 const subscriptionHandler = vi.fn()
456 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
457β
458 mutationObserver
459 .mutate('error', {
460 onError,
461 onSettled,
462 })
463 .catch(() => {})
464β
465 await vi.advanceTimersByTimeAsync(0)
466β
467 expect(onError).toHaveBeenCalledTimes(1)
468 expect(onSettled).toHaveBeenCalledTimes(1)
469β
470 expect(unhandledRejectionFn).toHaveBeenCalledTimes(2)
471 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(1, onErrorError)
472 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(2, onSettledError)
473β
474 expect(subscriptionHandler).toHaveBeenCalledTimes(2)
475β
476 unsubscribe()
477 })
478 })
479β
480 test('should not notify cache when setOptions is called with same options', () => {
481 const mutationObserver = new MutationObserver(queryClient, {
482 mutationFn: (text: string) => Promise.resolve(text),
483 })
484β
485 const notifySpy = vi.spyOn(queryClient.getMutationCache(), 'notify')
486β
487 const unsubscribe = mutationObserver.subscribe(() => undefined)
488β
489 notifySpy.mockClear()
490β
491 // Call setOptions with the same options
492 mutationObserver.setOptions({
493 mutationFn: mutationObserver.options.mutationFn,
494 })
495β
496 expect(notifySpy).not.toHaveBeenCalledWith(
497 expect.objectContaining({ type: 'observerOptionsUpdated' }),
498 )
499β
500 unsubscribe()
501 })
502})