Open History to see the last commit
1import { createKey, sleep } from '@tanstack/query-test-utils'
2import { fireEvent, render } from '@testing-library/react'
3import * as React from 'react'
4import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5import { QueryClient, useIsMutating, useMutation, useMutationState } from '..'
6import { renderWithClient } from './utils'
7import type { Mutation, MutationCacheNotifyEvent } from '..'
8β
9describe('useIsMutating', () => {
10 beforeEach(() => {
11 vi.useFakeTimers()
12 })
13β
14 afterEach(() => {
15 vi.useRealTimers()
16 })
17β
18 it('should return the number of fetching mutations', async () => {
19 const queryClient = new QueryClient()
20 const key1 = createKey()
21 const key2 = createKey()
22β
23 function IsMutating() {
24 const isMutating = useIsMutating()
25 return <div>mutating: {isMutating}</div>
26 }
27β
28 function Mutations() {
29 const { mutate: mutate1 } = useMutation({
30 mutationKey: key1,
31 mutationFn: () => sleep(50).then(() => 'data'),
32 })
33 const { mutate: mutate2 } = useMutation({
34 mutationKey: key2,
35 mutationFn: () => sleep(10).then(() => 'data'),
36 })
37β
38 return (
39 <div>
40 <button onClick={() => mutate1()}>mutate1</button>
41 <button onClick={() => mutate2()}>mutate2</button>
42 </div>
43 )
44 }
45β
46 function Page() {
47 return (
48 <div>
49 <IsMutating />
50 <Mutations />
51 </div>
52 )
53 }
54β
55 const rendered = renderWithClient(queryClient, <Page />)
56 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
57β
58 fireEvent.click(rendered.getByRole('button', { name: /mutate1/i }))
59 await vi.advanceTimersByTimeAsync(10)
60 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
61β
62 fireEvent.click(rendered.getByRole('button', { name: /mutate2/i }))
63 await vi.advanceTimersByTimeAsync(1)
64 expect(rendered.getByText('mutating: 2')).toBeInTheDocument()
65β
66 await vi.advanceTimersByTimeAsync(10)
67 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
68β
69 await vi.advanceTimersByTimeAsync(30)
70 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
71 })
72β
73 it('should update when the query client is cleared', async () => {
74 const queryClient = new QueryClient()
75β
76 function Page() {
77 const { mutate } = useMutation({
78 mutationFn: () => sleep(1000).then(() => 'data'),
79 })
80 const isMutating = useIsMutating()
81β
82 return (
83 <div>
84 <div>mutating: {isMutating}</div>
85 <button onClick={() => mutate()}>mutate</button>
86 <button onClick={() => queryClient.clear()}>clear</button>
87 </div>
88 )
89 }
90β
91 const rendered = renderWithClient(queryClient, <Page />)
92 fireEvent.click(rendered.getByRole('button', { name: 'mutate' }))
93 await vi.advanceTimersByTimeAsync(1)
94 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
95β
96 fireEvent.click(rendered.getByRole('button', { name: 'clear' }))
97 await vi.advanceTimersByTimeAsync(1)
98 expect(queryClient.isMutating()).toBe(0)
99 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
100β
101 await vi.advanceTimersByTimeAsync(1000)
102 })
103β
104 it('should filter correctly by mutationKey', async () => {
105 const queryClient = new QueryClient()
106 const key1 = createKey()
107 const key2 = createKey()
108β
109 function IsMutating() {
110 const isMutating = useIsMutating({ mutationKey: key1 })
111 return <div>mutating: {isMutating}</div>
112 }
113β
114 function Page() {
115 const { mutate: mutate1 } = useMutation({
116 mutationKey: key1,
117 mutationFn: () => sleep(100).then(() => 'data'),
118 })
119 const { mutate: mutate2 } = useMutation({
120 mutationKey: key2,
121 mutationFn: () => sleep(100).then(() => 'data'),
122 })
123β
124 React.useEffect(() => {
125 mutate1()
126 mutate2()
127 }, [mutate1, mutate2])
128β
129 return <IsMutating />
130 }
131β
132 const rendered = renderWithClient(queryClient, <Page />)
133 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
134β
135 await vi.advanceTimersByTimeAsync(1)
136 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
137β
138 await vi.advanceTimersByTimeAsync(100)
139 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
140 })
141β
142 it('should filter correctly by predicate', async () => {
143 const queryClient = new QueryClient()
144 const key1 = createKey()
145 const key2 = createKey()
146β
147 function IsMutating() {
148 const isMutating = useIsMutating({
149 predicate: (mutation) => mutation.options.mutationKey?.[0] === key1[0],
150 })
151 return <div>mutating: {isMutating}</div>
152 }
153β
154 function Page() {
155 const { mutate: mutate1 } = useMutation({
156 mutationKey: key1,
157 mutationFn: () => sleep(100).then(() => 'data'),
158 })
159 const { mutate: mutate2 } = useMutation({
160 mutationKey: key2,
161 mutationFn: () => sleep(100).then(() => 'data'),
162 })
163β
164 React.useEffect(() => {
165 mutate1()
166 mutate2()
167 }, [mutate1, mutate2])
168β
169 return <IsMutating />
170 }
171β
172 const rendered = renderWithClient(queryClient, <Page />)
173 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
174β
175 await vi.advanceTimersByTimeAsync(1)
176 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
177β
178 await vi.advanceTimersByTimeAsync(100)
179 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
180 })
181β
182 it('should use provided custom queryClient', async () => {
183 const queryClient = new QueryClient()
184 const key = createKey()
185β
186 function Page() {
187 const isMutating = useIsMutating({}, queryClient)
188 const { mutate } = useMutation(
189 {
190 mutationKey: key,
191 mutationFn: () => sleep(10).then(() => 'data'),
192 },
193 queryClient,
194 )
195β
196 React.useEffect(() => {
197 mutate()
198 }, [mutate])
199β
200 return (
201 <div>
202 <div>mutating: {isMutating}</div>
203 </div>
204 )
205 }
206β
207 const rendered = render(<Page />)
208β
209 await vi.advanceTimersByTimeAsync(0)
210 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
211 })
212β
213 it('should update when filters change without a cache update', async () => {
214 const queryClient = new QueryClient()
215 const key = createKey()
216 const otherKey = createKey()
217 const mutation = queryClient.getMutationCache().build(queryClient, {
218 mutationKey: key,
219 mutationFn: () => sleep(100),
220 })
221 const promise = mutation.execute(undefined)
222 await vi.advanceTimersByTimeAsync(0)
223β
224 function Page({ mutationKey }: { mutationKey: Array<string> }) {
225 const count = useIsMutating({ mutationKey })
226 return <div>mutating: {count}</div>
227 }
228β
229 const rendered = renderWithClient(queryClient, <Page mutationKey={key} />)
230 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
231β
232 rendered.rerender(<Page mutationKey={otherKey} />)
233 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
234β
235 await vi.advanceTimersByTimeAsync(100)
236 await promise
237 })
238})
239β
240describe('useMutationState', () => {
241 beforeEach(() => {
242 vi.useFakeTimers()
243 })
244β
245 afterEach(() => {
246 vi.useRealTimers()
247 })
248β
249 it('should update when filters change without a cache update', () => {
250 const queryClient = new QueryClient()
251 const key1 = createKey()
252 const key2 = createKey()
253 const cache = queryClient.getMutationCache()
254 cache.build(queryClient, { mutationKey: key1 })
255 cache.build(queryClient, { mutationKey: key2 })
256 const onCacheChange = vi.fn<(event: MutationCacheNotifyEvent) => void>()
257 const unsubscribe = cache.subscribe(onCacheChange)
258β
259 function Page({ mutationKey }: { mutationKey: Array<string> }) {
260 const keys = useMutationState({
261 filters: { mutationKey },
262 select: (mutation) => mutation.options.mutationKey,
263 })
264 return <div>keys: {JSON.stringify(keys)}</div>
265 }
266β
267 const rendered = renderWithClient(queryClient, <Page mutationKey={key1} />)
268 expect(
269 rendered.getByText(`keys: ${JSON.stringify([key1])}`),
270 ).toBeInTheDocument()
271β
272 rendered.rerender(<Page mutationKey={key2} />)
273 expect(
274 rendered.getByText(`keys: ${JSON.stringify([key2])}`),
275 ).toBeInTheDocument()
276β
277 rendered.rerender(<Page mutationKey={createKey()} />)
278 expect(rendered.getByText('keys: []')).toBeInTheDocument()
279 expect(onCacheChange).not.toHaveBeenCalled()
280 unsubscribe()
281 })
282β
283 it('should update when select changes without a cache update', () => {
284 const queryClient = new QueryClient()
285 const key = createKey()
286 queryClient.getMutationCache().build(queryClient, { mutationKey: key })
287β
288 function Page({ select }: { select: (mutation: Mutation) => unknown }) {
289 const result = useMutationState({ select })
290 return <div>result: {JSON.stringify(result)}</div>
291 }
292β
293 const rendered = renderWithClient(
294 queryClient,
295 <Page select={(mutation) => mutation.options.mutationKey} />,
296 )
297 expect(
298 rendered.getByText(`result: ${JSON.stringify([key])}`),
299 ).toBeInTheDocument()
300β
301 rendered.rerender(<Page select={(mutation) => mutation.state.status} />)
302 expect(rendered.getByText('result: ["idle"]')).toBeInTheDocument()
303 })
304β
305 it.each(['object', 'Date'] as const)(
306 'should recompute %s results on rerender with stable filters and select',
307 (resultType) => {
308 const queryClient = new QueryClient()
309 const key = createKey()
310 const cache = queryClient.getMutationCache()
311 const existingMutation = cache.build(queryClient, {
312 mutationKey: key,
313 meta: { time: 0 },
314 })
315 const state = existingMutation.state
316 const filters = { mutationKey: key }
317 const select = (mutation: Mutation) =>
318 resultType === 'Date'
319 ? new Date(Number(mutation.meta?.time))
320 : { time: mutation.meta?.time }
321 const options = { filters, select }
322 const onCacheChange = vi.fn<(event: MutationCacheNotifyEvent) => void>()
323 const unsubscribe = cache.subscribe(onCacheChange)
324β
325 function Page() {
326 const result = useMutationState(options)
327 return <div>result: {JSON.stringify(result)}</div>
328 }
329β
330 const rendered = renderWithClient(queryClient, <Page />)
331 expect(
332 rendered.getByText(
333 resultType === 'Date'
334 ? 'result: ["1970-01-01T00:00:00.000Z"]'
335 : 'result: [{"time":0}]',
336 ),
337 ).toBeInTheDocument()
338β
339 existingMutation.setOptions({
340 ...existingMutation.options,
341 meta: { time: 1000 },
342 })
343 rendered.rerender(<Page />)
344 expect(
345 rendered.getByText(
346 resultType === 'Date'
347 ? 'result: ["1970-01-01T00:00:01.000Z"]'
348 : 'result: [{"time":1000}]',
349 ),
350 ).toBeInTheDocument()
351 expect(existingMutation.state).toBe(state)
352 expect(onCacheChange).not.toHaveBeenCalled()
353 unsubscribe()
354 },
355 )
356β
357 it('should render selector results that cannot be structurally shared', () => {
358 const queryClient = new QueryClient()
359 const key = createKey()
360 queryClient.getMutationCache().build(queryClient, { mutationKey: key })
361β
362 function Page({ time }: { time: number }) {
363 const result = useMutationState({
364 filters: { mutationKey: key },
365 select: () => new Date(time),
366 })
367β
368 return <div>date: {result[0]?.toISOString()}</div>
369 }
370β
371 const rendered = renderWithClient(queryClient, <Page time={0} />)
372 expect(
373 rendered.getByText('date: 1970-01-01T00:00:00.000Z'),
374 ).toBeInTheDocument()
375β
376 rendered.rerender(<Page time={1000} />)
377 expect(
378 rendered.getByText('date: 1970-01-01T00:00:01.000Z'),
379 ).toBeInTheDocument()
380 })
381β
382 it('should update Date selector results when mutation state changes', async () => {
383 const queryClient = new QueryClient()
384 const key = createKey()
385 const filters = { mutationKey: key }
386 const select = (mutation: Mutation) =>
387 new Date(mutation.state.status === 'success' ? 1000 : 0)
388β
389 function Dates() {
390 const { mutate } = useMutation({
391 mutationKey: key,
392 mutationFn: () => sleep(10),
393 })
394 const result = useMutationState({ filters, select })
395 return (
396 <div>
397 <div>dates: {JSON.stringify(result)}</div>
398 <button onClick={() => mutate()}>mutate</button>
399 </div>
400 )
401 }
402β
403 const rendered = renderWithClient(queryClient, <Dates />)
404 expect(rendered.getByText('dates: []')).toBeInTheDocument()
405β
406 fireEvent.click(rendered.getByRole('button', { name: 'mutate' }))
407 await vi.advanceTimersByTimeAsync(1)
408 expect(
409 rendered.getByText('dates: ["1970-01-01T00:00:00.000Z"]'),
410 ).toBeInTheDocument()
411β
412 await vi.advanceTimersByTimeAsync(10)
413 expect(
414 rendered.getByText('dates: ["1970-01-01T00:00:01.000Z"]'),
415 ).toBeInTheDocument()
416 })
417β
418 it('should update when only the mutation state changes', async () => {
419 const queryClient = new QueryClient()
420 const key = createKey()
421 const filters = { mutationKey: key }
422 const select = (mutation: Mutation) => mutation.state.status
423β
424 function Statuses() {
425 const result = useMutationState({ filters, select })
426 return <div>statuses: {JSON.stringify(result)}</div>
427 }
428β
429 function Mutate() {
430 const { mutate } = useMutation({
431 mutationKey: key,
432 mutationFn: () => sleep(10),
433 })
434 return <button onClick={() => mutate()}>mutate</button>
435 }
436β
437 const rendered = renderWithClient(
438 queryClient,
439 <div>
440 <Statuses />
441 <Mutate />
442 </div>,
443 )
444 expect(rendered.getByText('statuses: []')).toBeInTheDocument()
445β
446 fireEvent.click(rendered.getByRole('button', { name: 'mutate' }))
447 await vi.advanceTimersByTimeAsync(1)
448 expect(rendered.getByText('statuses: ["pending"]')).toBeInTheDocument()
449β
450 await vi.advanceTimersByTimeAsync(10)
451 expect(rendered.getByText('statuses: ["success"]')).toBeInTheDocument()
452 })
453β
454 it.each(['stable', 'inline'] as const)(
455 'should preserve the result reference with %s inputs',
456 (inputs) => {
457 const queryClient = new QueryClient()
458 const key = createKey()
459 queryClient.getMutationCache().build(queryClient, { mutationKey: key })
460 const onResult =
461 vi.fn<
462 (result: Array<{ key: ReadonlyArray<unknown> | undefined }>) => void
463 >()
464 const filters = { status: 'idle' as const }
465 const select = (mutation: Mutation) => ({
466 key: mutation.options.mutationKey,
467 })
468β
469 function Page() {
470 const result = useMutationState({
471 filters: inputs === 'inline' ? { ...filters } : filters,
472 select: inputs === 'inline' ? (mutation) => select(mutation) : select,
473 })
474 React.useEffect(() => {
475 onResult(result)
476 }, [result])
477 return <div>result: {JSON.stringify(result)}</div>
478 }
479β
480 const rendered = renderWithClient(queryClient, <Page />)
481 const expected = `result: ${JSON.stringify([{ key }])}`
482 expect(rendered.getByText(expected)).toBeInTheDocument()
483 expect(onResult).toHaveBeenCalledTimes(1)
484β
485 rendered.rerender(<Page />)
486 expect(rendered.getByText(expected)).toBeInTheDocument()
487 expect(onResult).toHaveBeenCalledTimes(1)
488 },
489 )
490β
491 it('should read from a changed custom queryClient', () => {
492 const client1 = new QueryClient()
493 const client2 = new QueryClient()
494 const key1 = createKey()
495 const key2 = createKey()
496 client1.getMutationCache().build(client1, { mutationKey: key1 })
497 client2.getMutationCache().build(client2, { mutationKey: key2 })
498 const select = (mutation: Mutation) => mutation.options.mutationKey
499β
500 function Page({ client }: { client: QueryClient }) {
501 const keys = useMutationState({ select }, client)
502 return <div>keys: {JSON.stringify(keys)}</div>
503 }
504β
505 const rendered = render(<Page client={client1} />)
506 expect(
507 rendered.getByText(`keys: ${JSON.stringify([key1])}`),
508 ).toBeInTheDocument()
509β
510 rendered.rerender(<Page client={client2} />)
511 expect(
512 rendered.getByText(`keys: ${JSON.stringify([key2])}`),
513 ).toBeInTheDocument()
514 expect(client1.getMutationCache().hasListeners()).toBe(false)
515 expect(client2.getMutationCache().hasListeners()).toBe(true)
516 })
517β
518 it('should remove successful mutations when the query client is cleared', async () => {
519 const queryClient = new QueryClient()
520β
521 function Page() {
522 const { mutate } = useMutation({
523 mutationFn: () => Promise.resolve('saved'),
524 })
525 const data = useMutationState({
526 filters: { status: 'success' },
527 select: (mutation) => mutation.state.data,
528 })
529β
530 return (
531 <div>
532 <div>data: {JSON.stringify(data)}</div>
533 <button onClick={() => mutate()}>mutate</button>
534 <button onClick={() => queryClient.clear()}>clear</button>
535 </div>
536 )
537 }
538β
539 const rendered = renderWithClient(queryClient, <Page />)
540 fireEvent.click(rendered.getByRole('button', { name: 'mutate' }))
541 await vi.advanceTimersByTimeAsync(1)
542 expect(rendered.getByText('data: ["saved"]')).toBeInTheDocument()
543β
544 fireEvent.click(rendered.getByRole('button', { name: 'clear' }))
545 await vi.advanceTimersByTimeAsync(1)
546 expect(queryClient.getMutationCache().getAll()).toStrictEqual([])
547 expect(rendered.getByText('data: []')).toBeInTheDocument()
548 })
549β
550 it('should return variables after calling mutate', async () => {
551 const queryClient = new QueryClient()
552 const mutationKey = ['mutation']
553β
554 function Variables() {
555 const variables = useMutationState({
556 filters: { mutationKey, status: 'pending' },
557 select: (mutation) => mutation.state.variables,
558 })
559β
560 return <div>variables: {JSON.stringify(variables)}</div>
561 }
562β
563 function Mutate() {
564 const { mutate, data } = useMutation({
565 mutationKey,
566 mutationFn: (input: number) => sleep(150).then(() => `data${input}`),
567 })
568β
569 return (
570 <div>
571 data: {data ?? 'null'}
572 <button onClick={() => mutate(1)}>mutate</button>
573 </div>
574 )
575 }
576β
577 function Page() {
578 return (
579 <div>
580 <Variables />
581 <Mutate />
582 </div>
583 )
584 }
585β
586 const rendered = renderWithClient(queryClient, <Page />)
587β
588 expect(rendered.getByText('data: null')).toBeInTheDocument()
589 expect(rendered.getByText('variables: []')).toBeInTheDocument()
590β
591 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
592 await vi.advanceTimersByTimeAsync(1)
593 expect(rendered.getByText('variables: [1]')).toBeInTheDocument()
594β
595 await vi.advanceTimersByTimeAsync(150)
596 expect(rendered.getByText('data: data1')).toBeInTheDocument()
597 expect(rendered.getByText('variables: []')).toBeInTheDocument()
598 })
599})