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

mutationObserver.test.tsx

502 lines13.4 KB

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})