Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { MutationObserver } from '../mutationObserver'
3import { createQueryClient, executeMutation, queryKey, sleep } from './utils'
4import type { QueryClient } from '..'
5import type { MutationState } from '../mutation'
6β
7describe('mutations', () => {
8 let queryClient: QueryClient
9β
10 beforeEach(() => {
11 vi.useFakeTimers()
12 queryClient = createQueryClient()
13 queryClient.mount()
14 })
15β
16 afterEach(() => {
17 queryClient.clear()
18 vi.useRealTimers()
19 })
20β
21 test('mutate should accept null values', async () => {
22 let variables
23β
24 const mutation = new MutationObserver(queryClient, {
25 mutationFn: (vars: unknown) => {
26 variables = vars
27 return Promise.resolve(vars)
28 },
29 })
30β
31 await mutation.mutate(null)
32β
33 expect(variables).toBe(null)
34 })
35β
36 test('setMutationDefaults should be able to set defaults', async () => {
37 const key = queryKey()
38 const fn = vi.fn()
39β
40 queryClient.setMutationDefaults(key, {
41 mutationFn: fn,
42 })
43β
44 await executeMutation(
45 queryClient,
46 {
47 mutationKey: key,
48 },
49 'vars',
50 )
51β
52 expect(fn).toHaveBeenCalledTimes(1)
53 expect(fn).toHaveBeenCalledWith('vars')
54 })
55β
56 test('mutation should set correct success states', async () => {
57 const mutation = new MutationObserver(queryClient, {
58 mutationFn: (text: string) => sleep(10).then(() => text),
59 onMutate: (text) => text,
60 })
61β
62 expect(mutation.getCurrentResult()).toEqual({
63 context: undefined,
64 data: undefined,
65 error: null,
66 failureCount: 0,
67 failureReason: null,
68 isError: false,
69 isIdle: true,
70 isPending: false,
71 isPaused: false,
72 isSuccess: false,
73 mutate: expect.any(Function),
74 reset: expect.any(Function),
75 status: 'idle',
76 variables: undefined,
77 submittedAt: 0,
78 })
79β
80 const states: Array<MutationState<string, unknown, string, string>> = []
81β
82 mutation.subscribe((state) => {
83 states.push(state)
84 })
85β
86 mutation.mutate('todo')
87β
88 await vi.advanceTimersByTimeAsync(0)
89β
90 expect(states[0]).toEqual({
91 context: undefined,
92 data: undefined,
93 error: null,
94 failureCount: 0,
95 failureReason: null,
96 isError: false,
97 isIdle: false,
98 isPending: true,
99 isPaused: false,
100 isSuccess: false,
101 mutate: expect.any(Function),
102 reset: expect.any(Function),
103 status: 'pending',
104 variables: 'todo',
105 submittedAt: expect.any(Number),
106 })
107β
108 await vi.advanceTimersByTimeAsync(5)
109β
110 expect(states[1]).toEqual({
111 context: 'todo',
112 data: undefined,
113 error: null,
114 failureCount: 0,
115 failureReason: null,
116 isError: false,
117 isIdle: false,
118 isPending: true,
119 isPaused: false,
120 isSuccess: false,
121 mutate: expect.any(Function),
122 reset: expect.any(Function),
123 status: 'pending',
124 variables: 'todo',
125 submittedAt: expect.any(Number),
126 })
127β
128 await vi.advanceTimersByTimeAsync(20)
129β
130 expect(states[2]).toEqual({
131 context: 'todo',
132 data: 'todo',
133 error: null,
134 failureCount: 0,
135 failureReason: null,
136 isError: false,
137 isIdle: false,
138 isPending: false,
139 isPaused: false,
140 isSuccess: true,
141 mutate: expect.any(Function),
142 reset: expect.any(Function),
143 status: 'success',
144 variables: 'todo',
145 submittedAt: expect.any(Number),
146 })
147 })
148β
149 test('mutation should set correct error states', async () => {
150 const mutation = new MutationObserver(queryClient, {
151 mutationFn: (_: string) =>
152 sleep(20).then(() => Promise.reject(new Error('err'))),
153 onMutate: (text) => text,
154 retry: 1,
155 retryDelay: 1,
156 })
157β
158 const states: Array<MutationState<string, unknown, string, string>> = []
159β
160 mutation.subscribe((state) => {
161 states.push(state)
162 })
163β
164 mutation.mutate('todo').catch(() => undefined)
165β
166 await vi.advanceTimersByTimeAsync(0)
167β
168 expect(states[0]).toEqual({
169 context: undefined,
170 data: undefined,
171 error: null,
172 failureCount: 0,
173 failureReason: null,
174 isError: false,
175 isIdle: false,
176 isPending: true,
177 isPaused: false,
178 isSuccess: false,
179 mutate: expect.any(Function),
180 reset: expect.any(Function),
181 status: 'pending',
182 variables: 'todo',
183 submittedAt: expect.any(Number),
184 })
185β
186 await vi.advanceTimersByTimeAsync(10)
187β
188 expect(states[1]).toEqual({
189 context: 'todo',
190 data: undefined,
191 error: null,
192 failureCount: 0,
193 failureReason: null,
194 isError: false,
195 isIdle: false,
196 isPending: true,
197 isPaused: false,
198 isSuccess: false,
199 mutate: expect.any(Function),
200 reset: expect.any(Function),
201 status: 'pending',
202 variables: 'todo',
203 submittedAt: expect.any(Number),
204 })
205β
206 await vi.advanceTimersByTimeAsync(20)
207β
208 expect(states[2]).toEqual({
209 context: 'todo',
210 data: undefined,
211 error: null,
212 failureCount: 1,
213 failureReason: new Error('err'),
214 isError: false,
215 isIdle: false,
216 isPending: true,
217 isPaused: false,
218 isSuccess: false,
219 mutate: expect.any(Function),
220 reset: expect.any(Function),
221 status: 'pending',
222 variables: 'todo',
223 submittedAt: expect.any(Number),
224 })
225β
226 await vi.advanceTimersByTimeAsync(30)
227β
228 expect(states[3]).toEqual({
229 context: 'todo',
230 data: undefined,
231 error: new Error('err'),
232 failureCount: 2,
233 failureReason: new Error('err'),
234 isError: true,
235 isIdle: false,
236 isPending: false,
237 isPaused: false,
238 isSuccess: false,
239 mutate: expect.any(Function),
240 reset: expect.any(Function),
241 status: 'error',
242 variables: 'todo',
243 submittedAt: expect.any(Number),
244 })
245 })
246β
247 test('should be able to restore a mutation', async () => {
248 const key = queryKey()
249β
250 const onMutate = vi.fn()
251 const onSuccess = vi.fn()
252 const onSettled = vi.fn()
253β
254 queryClient.setMutationDefaults(key, {
255 mutationFn: (text: string) => sleep(10).then(() => text),
256 onMutate,
257 onSuccess,
258 onSettled,
259 })
260β
261 const mutation = queryClient
262 .getMutationCache()
263 .build<string, unknown, string, string>(
264 queryClient,
265 {
266 mutationKey: key,
267 },
268 {
269 context: 'todo',
270 data: undefined,
271 error: null,
272 failureCount: 1,
273 failureReason: 'err',
274 isPaused: true,
275 status: 'pending',
276 variables: 'todo',
277 submittedAt: 1,
278 },
279 )
280β
281 expect(mutation.state).toEqual({
282 context: 'todo',
283 data: undefined,
284 error: null,
285 failureCount: 1,
286 failureReason: 'err',
287 isPaused: true,
288 status: 'pending',
289 variables: 'todo',
290 submittedAt: 1,
291 })
292β
293 void queryClient.resumePausedMutations()
294 await vi.advanceTimersByTimeAsync(0)
295β
296 // check that the mutation is correctly resumed
297 expect(mutation.state).toEqual({
298 context: 'todo',
299 data: undefined,
300 error: null,
301 failureCount: 1,
302 failureReason: 'err',
303 isPaused: false,
304 status: 'pending',
305 variables: 'todo',
306 submittedAt: 1,
307 })
308β
309 await vi.advanceTimersByTimeAsync(20)
310β
311 expect(mutation.state).toEqual({
312 context: 'todo',
313 data: 'todo',
314 error: null,
315 failureCount: 0,
316 failureReason: null,
317 isPaused: false,
318 status: 'success',
319 variables: 'todo',
320 submittedAt: 1,
321 })
322β
323 expect(onMutate).not.toHaveBeenCalled()
324 expect(onSuccess).toHaveBeenCalled()
325 expect(onSettled).toHaveBeenCalled()
326 })
327β
328 test('addObserver should not add an existing observer', () => {
329 const mutationCache = queryClient.getMutationCache()
330 const observer = new MutationObserver(queryClient, {})
331 const currentMutation = mutationCache.build(queryClient, {})
332β
333 const fn = vi.fn()
334β
335 const unsubscribe = mutationCache.subscribe((event) => {
336 fn(event.type)
337 })
338β
339 currentMutation.addObserver(observer)
340 currentMutation.addObserver(observer)
341β
342 expect(fn).toHaveBeenCalledTimes(1)
343 expect(fn).toHaveBeenCalledWith('observerAdded')
344β
345 unsubscribe()
346 })
347β
348 test('mutate should throw an error if no mutationFn found', async () => {
349 const mutation = new MutationObserver(queryClient, {
350 mutationFn: undefined,
351 retry: false,
352 })
353β
354 let error: any
355 try {
356 await mutation.mutate()
357 } catch (err) {
358 error = err
359 }
360 expect(error).toEqual(new Error('No mutationFn found'))
361 })
362β
363 test('mutate update the mutation state even without an active subscription 1', async () => {
364 const onSuccess = vi.fn()
365 const onSettled = vi.fn()
366β
367 const mutation = new MutationObserver(queryClient, {
368 mutationFn: () => {
369 return Promise.resolve('update')
370 },
371 })
372β
373 await mutation.mutate(undefined, { onSuccess, onSettled })
374 expect(mutation.getCurrentResult().data).toEqual('update')
375 expect(onSuccess).not.toHaveBeenCalled()
376 expect(onSettled).not.toHaveBeenCalled()
377 })
378β
379 test('mutate update the mutation state even without an active subscription 2', async () => {
380 const onSuccess = vi.fn()
381 const onSettled = vi.fn()
382β
383 const mutation = new MutationObserver(queryClient, {
384 mutationFn: () => {
385 return Promise.resolve('update')
386 },
387 })
388β
389 await mutation.mutate(undefined, { onSuccess, onSettled })
390 expect(mutation.getCurrentResult().data).toEqual('update')
391 expect(onSuccess).not.toHaveBeenCalled()
392 expect(onSettled).not.toHaveBeenCalled()
393 })
394β
395 test('mutation callbacks should see updated options', async () => {
396 const onSuccess = vi.fn()
397β
398 const mutation = new MutationObserver(queryClient, {
399 mutationFn: () => {
400 sleep(100)
401 return Promise.resolve('update')
402 },
403 onSuccess: () => {
404 onSuccess(1)
405 },
406 })
407β
408 void mutation.mutate()
409β
410 mutation.setOptions({
411 mutationFn: () => {
412 sleep(100)
413 return Promise.resolve('update')
414 },
415 onSuccess: () => {
416 onSuccess(2)
417 },
418 })
419β
420 await vi.waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1))
421β
422 expect(onSuccess).toHaveBeenCalledWith(2)
423 })
424β
425 describe('scoped mutations', () => {
426 test('mutations in the same scope should run in serial', async () => {
427 const key1 = queryKey()
428 const key2 = queryKey()
429β
430 const results: Array<string> = []
431β
432 executeMutation(
433 queryClient,
434 {
435 mutationKey: key1,
436 scope: {
437 id: 'scope',
438 },
439 mutationFn: async () => {
440 results.push('start-A')
441 await sleep(10)
442 results.push('finish-A')
443 return 'a'
444 },
445 },
446 'vars1',
447 )
448β
449 expect(
450 queryClient.getMutationCache().find({ mutationKey: key1 })?.state,
451 ).toMatchObject({
452 status: 'pending',
453 isPaused: false,
454 })
455β
456 executeMutation(
457 queryClient,
458 {
459 mutationKey: key2,
460 scope: {
461 id: 'scope',
462 },
463 mutationFn: async () => {
464 results.push('start-B')
465 await sleep(10)
466 results.push('finish-B')
467 return 'b'
468 },
469 },
470 'vars2',
471 )
472β
473 expect(
474 queryClient.getMutationCache().find({ mutationKey: key2 })?.state,
475 ).toMatchObject({
476 status: 'pending',
477 isPaused: true,
478 })
479β
480 await vi.runAllTimersAsync()
481β
482 expect(results).toStrictEqual([
483 'start-A',
484 'finish-A',
485 'start-B',
486 'finish-B',
487 ])
488 })
489 })
490β
491 test('mutations without scope should run in parallel', async () => {
492 const key1 = queryKey()
493 const key2 = queryKey()
494β
495 const results: Array<string> = []
496β
497 executeMutation(
498 queryClient,
499 {
500 mutationKey: key1,
501 mutationFn: async () => {
502 results.push('start-A')
503 await sleep(10)
504 results.push('finish-A')
505 return 'a'
506 },
507 },
508 'vars1',
509 )
510β
511 executeMutation(
512 queryClient,
513 {
514 mutationKey: key2,
515 mutationFn: async () => {
516 results.push('start-B')
517 await sleep(10)
518 results.push('finish-B')
519 return 'b'
520 },
521 },
522 'vars2',
523 )
524β
525 await vi.runAllTimersAsync()
526β
527 expect(results).toStrictEqual([
528 'start-A',
529 'start-B',
530 'finish-A',
531 'finish-B',
532 ])
533 })
534β
535 test('each scope should run should run in parallel, serial within scope', async () => {
536 const results: Array<string> = []
537β
538 executeMutation(
539 queryClient,
540 {
541 scope: {
542 id: '1',
543 },
544 mutationFn: async () => {
545 results.push('start-A1')
546 await sleep(10)
547 results.push('finish-A1')
548 return 'a'
549 },
550 },
551 'vars1',
552 )
553β
554 executeMutation(
555 queryClient,
556 {
557 scope: {
558 id: '1',
559 },
560 mutationFn: async () => {
561 results.push('start-B1')
562 await sleep(10)
563 results.push('finish-B1')
564 return 'b'
565 },
566 },
567 'vars2',
568 )
569β
570 executeMutation(
571 queryClient,
572 {
573 scope: {
574 id: '2',
575 },
576 mutationFn: async () => {
577 results.push('start-A2')
578 await sleep(10)
579 results.push('finish-A2')
580 return 'a'
581 },
582 },
583 'vars1',
584 )
585β
586 executeMutation(
587 queryClient,
588 {
589 scope: {
590 id: '2',
591 },
592 mutationFn: async () => {
593 results.push('start-B2')
594 await sleep(10)
595 results.push('finish-B2')
596 return 'b'
597 },
598 },
599 'vars2',
600 )
601β
602 await vi.runAllTimersAsync()
603β
604 expect(results).toStrictEqual([
605 'start-A1',
606 'start-A2',
607 'finish-A1',
608 'start-B1',
609 'finish-A2',
610 'start-B2',
611 'finish-B1',
612 'finish-B2',
613 ])
614 })
615})