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) => Promise.resolve(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 await queryClient.resumePausedMutations()
294β
295 expect(mutation.state).toEqual({
296 context: 'todo',
297 data: 'todo',
298 error: null,
299 failureCount: 0,
300 failureReason: null,
301 isPaused: false,
302 status: 'success',
303 variables: 'todo',
304 submittedAt: 1,
305 })
306β
307 expect(onMutate).not.toHaveBeenCalled()
308 expect(onSuccess).toHaveBeenCalled()
309 expect(onSettled).toHaveBeenCalled()
310 })
311β
312 test('addObserver should not add an existing observer', () => {
313 const mutationCache = queryClient.getMutationCache()
314 const observer = new MutationObserver(queryClient, {})
315 const currentMutation = mutationCache.build(queryClient, {})
316β
317 const fn = vi.fn()
318β
319 const unsubscribe = mutationCache.subscribe((event) => {
320 fn(event.type)
321 })
322β
323 currentMutation.addObserver(observer)
324 currentMutation.addObserver(observer)
325β
326 expect(fn).toHaveBeenCalledTimes(1)
327 expect(fn).toHaveBeenCalledWith('observerAdded')
328β
329 unsubscribe()
330 })
331β
332 test('mutate should throw an error if no mutationFn found', async () => {
333 const mutation = new MutationObserver(queryClient, {
334 mutationFn: undefined,
335 retry: false,
336 })
337β
338 let error: any
339 try {
340 await mutation.mutate()
341 } catch (err) {
342 error = err
343 }
344 expect(error).toEqual(new Error('No mutationFn found'))
345 })
346β
347 test('mutate update the mutation state even without an active subscription 1', async () => {
348 const onSuccess = vi.fn()
349 const onSettled = vi.fn()
350β
351 const mutation = new MutationObserver(queryClient, {
352 mutationFn: () => {
353 return Promise.resolve('update')
354 },
355 })
356β
357 await mutation.mutate(undefined, { onSuccess, onSettled })
358 expect(mutation.getCurrentResult().data).toEqual('update')
359 expect(onSuccess).not.toHaveBeenCalled()
360 expect(onSettled).not.toHaveBeenCalled()
361 })
362β
363 test('mutate update the mutation state even without an active subscription 2', 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('mutation callbacks should see updated options', async () => {
380 const onSuccess = vi.fn()
381β
382 const mutation = new MutationObserver(queryClient, {
383 mutationFn: () => {
384 sleep(100)
385 return Promise.resolve('update')
386 },
387 onSuccess: () => {
388 onSuccess(1)
389 },
390 })
391β
392 void mutation.mutate()
393β
394 mutation.setOptions({
395 mutationFn: () => {
396 sleep(100)
397 return Promise.resolve('update')
398 },
399 onSuccess: () => {
400 onSuccess(2)
401 },
402 })
403β
404 await vi.waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1))
405β
406 expect(onSuccess).toHaveBeenCalledWith(2)
407 })
408β
409 describe('scoped mutations', () => {
410 test('mutations in the same scope should run in serial', async () => {
411 const key1 = queryKey()
412 const key2 = queryKey()
413β
414 const results: Array<string> = []
415β
416 executeMutation(
417 queryClient,
418 {
419 mutationKey: key1,
420 scope: {
421 id: 'scope',
422 },
423 mutationFn: async () => {
424 results.push('start-A')
425 await sleep(10)
426 results.push('finish-A')
427 return 'a'
428 },
429 },
430 'vars1',
431 )
432β
433 expect(
434 queryClient.getMutationCache().find({ mutationKey: key1 })?.state,
435 ).toMatchObject({
436 status: 'pending',
437 isPaused: false,
438 })
439β
440 executeMutation(
441 queryClient,
442 {
443 mutationKey: key2,
444 scope: {
445 id: 'scope',
446 },
447 mutationFn: async () => {
448 results.push('start-B')
449 await sleep(10)
450 results.push('finish-B')
451 return 'b'
452 },
453 },
454 'vars2',
455 )
456β
457 expect(
458 queryClient.getMutationCache().find({ mutationKey: key2 })?.state,
459 ).toMatchObject({
460 status: 'pending',
461 isPaused: true,
462 })
463β
464 await vi.runAllTimersAsync()
465β
466 expect(results).toStrictEqual([
467 'start-A',
468 'finish-A',
469 'start-B',
470 'finish-B',
471 ])
472 })
473 })
474β
475 test('mutations without scope should run in parallel', async () => {
476 const key1 = queryKey()
477 const key2 = queryKey()
478β
479 const results: Array<string> = []
480β
481 executeMutation(
482 queryClient,
483 {
484 mutationKey: key1,
485 mutationFn: async () => {
486 results.push('start-A')
487 await sleep(10)
488 results.push('finish-A')
489 return 'a'
490 },
491 },
492 'vars1',
493 )
494β
495 executeMutation(
496 queryClient,
497 {
498 mutationKey: key2,
499 mutationFn: async () => {
500 results.push('start-B')
501 await sleep(10)
502 results.push('finish-B')
503 return 'b'
504 },
505 },
506 'vars2',
507 )
508β
509 await vi.runAllTimersAsync()
510β
511 expect(results).toStrictEqual([
512 'start-A',
513 'start-B',
514 'finish-A',
515 'finish-B',
516 ])
517 })
518β
519 test('each scope should run should run in parallel, serial within scope', async () => {
520 const results: Array<string> = []
521β
522 executeMutation(
523 queryClient,
524 {
525 scope: {
526 id: '1',
527 },
528 mutationFn: async () => {
529 results.push('start-A1')
530 await sleep(10)
531 results.push('finish-A1')
532 return 'a'
533 },
534 },
535 'vars1',
536 )
537β
538 executeMutation(
539 queryClient,
540 {
541 scope: {
542 id: '1',
543 },
544 mutationFn: async () => {
545 results.push('start-B1')
546 await sleep(10)
547 results.push('finish-B1')
548 return 'b'
549 },
550 },
551 'vars2',
552 )
553β
554 executeMutation(
555 queryClient,
556 {
557 scope: {
558 id: '2',
559 },
560 mutationFn: async () => {
561 results.push('start-A2')
562 await sleep(10)
563 results.push('finish-A2')
564 return 'a'
565 },
566 },
567 'vars1',
568 )
569β
570 executeMutation(
571 queryClient,
572 {
573 scope: {
574 id: '2',
575 },
576 mutationFn: async () => {
577 results.push('start-B2')
578 await sleep(10)
579 results.push('finish-B2')
580 return 'b'
581 },
582 },
583 'vars2',
584 )
585β
586 await vi.runAllTimersAsync()
587β
588 expect(results).toStrictEqual([
589 'start-A1',
590 'start-A2',
591 'finish-A1',
592 'start-B1',
593 'finish-A2',
594 'start-B2',
595 'finish-B1',
596 'finish-B2',
597 ])
598 })
599})