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

useMutationState.test.tsx

596 lines18.4 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { fireEvent, render } from '@testing-library/react'
3import * as React from 'react'
4import { queryKey, sleep } from '@tanstack/query-test-utils'
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 = queryKey()
21 const key2 = queryKey()
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 = queryKey()
107 const key2 = queryKey()
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 = queryKey()
145 const key2 = queryKey()
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 = queryKey()
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 = queryKey()
216 const otherKey = queryKey()
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 = queryKey()
252 const key2 = queryKey()
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={queryKey()} />)
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 = queryKey()
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 = queryKey()
310 const cache = queryClient.getMutationCache()
311 const mutation = cache.build(queryClient, {
312 mutationKey: key,
313 meta: { time: 0 },
314 })
315 const state = mutation.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 mutation.setOptions({ ...mutation.options, meta: { time: 1000 } })
340 rendered.rerender(<Page />)
341 expect(
342 rendered.getByText(
343 resultType === 'Date'
344 ? 'result: ["1970-01-01T00:00:01.000Z"]'
345 : 'result: [{"time":1000}]',
346 ),
347 ).toBeInTheDocument()
348 expect(mutation.state).toBe(state)
349 expect(onCacheChange).not.toHaveBeenCalled()
350 unsubscribe()
351 },
352 )
353​
354 it('should render selector results that cannot be structurally shared', () => {
355 const queryClient = new QueryClient()
356 const key = queryKey()
357 queryClient.getMutationCache().build(queryClient, { mutationKey: key })
358​
359 function Page({ time }: { time: number }) {
360 const result = useMutationState({
361 filters: { mutationKey: key },
362 select: () => new Date(time),
363 })
364​
365 return <div>date: {result[0]?.toISOString()}</div>
366 }
367​
368 const rendered = renderWithClient(queryClient, <Page time={0} />)
369 expect(
370 rendered.getByText('date: 1970-01-01T00:00:00.000Z'),
371 ).toBeInTheDocument()
372​
373 rendered.rerender(<Page time={1000} />)
374 expect(
375 rendered.getByText('date: 1970-01-01T00:00:01.000Z'),
376 ).toBeInTheDocument()
377 })
378​
379 it('should update Date selector results when mutation state changes', async () => {
380 const queryClient = new QueryClient()
381 const key = queryKey()
382 const filters = { mutationKey: key }
383 const select = (mutation: Mutation) =>
384 new Date(mutation.state.status === 'success' ? 1000 : 0)
385​
386 function Dates() {
387 const { mutate } = useMutation({
388 mutationKey: key,
389 mutationFn: () => sleep(10),
390 })
391 const result = useMutationState({ filters, select })
392 return (
393 <div>
394 <div>dates: {JSON.stringify(result)}</div>
395 <button onClick={() => mutate()}>mutate</button>
396 </div>
397 )
398 }
399​
400 const rendered = renderWithClient(queryClient, <Dates />)
401 expect(rendered.getByText('dates: []')).toBeInTheDocument()
402​
403 fireEvent.click(rendered.getByRole('button', { name: 'mutate' }))
404 await vi.advanceTimersByTimeAsync(1)
405 expect(
406 rendered.getByText('dates: ["1970-01-01T00:00:00.000Z"]'),
407 ).toBeInTheDocument()
408​
409 await vi.advanceTimersByTimeAsync(10)
410 expect(
411 rendered.getByText('dates: ["1970-01-01T00:00:01.000Z"]'),
412 ).toBeInTheDocument()
413 })
414​
415 it('should update when only the mutation state changes', async () => {
416 const queryClient = new QueryClient()
417 const key = queryKey()
418 const filters = { mutationKey: key }
419 const select = (mutation: Mutation) => mutation.state.status
420​
421 function Statuses() {
422 const result = useMutationState({ filters, select })
423 return <div>statuses: {JSON.stringify(result)}</div>
424 }
425​
426 function Mutate() {
427 const { mutate } = useMutation({
428 mutationKey: key,
429 mutationFn: () => sleep(10),
430 })
431 return <button onClick={() => mutate()}>mutate</button>
432 }
433​
434 const rendered = renderWithClient(
435 queryClient,
436 <div>
437 <Statuses />
438 <Mutate />
439 </div>,
440 )
441 expect(rendered.getByText('statuses: []')).toBeInTheDocument()
442​
443 fireEvent.click(rendered.getByRole('button', { name: 'mutate' }))
444 await vi.advanceTimersByTimeAsync(1)
445 expect(rendered.getByText('statuses: ["pending"]')).toBeInTheDocument()
446​
447 await vi.advanceTimersByTimeAsync(10)
448 expect(rendered.getByText('statuses: ["success"]')).toBeInTheDocument()
449 })
450​
451 it.each(['stable', 'inline'] as const)(
452 'should preserve the result reference with %s inputs',
453 (inputs) => {
454 const queryClient = new QueryClient()
455 const key = queryKey()
456 queryClient.getMutationCache().build(queryClient, { mutationKey: key })
457 const onResult =
458 vi.fn<
459 (result: Array<{ key: ReadonlyArray<unknown> | undefined }>) => void
460 >()
461 const filters = { status: 'idle' as const }
462 const select = (mutation: Mutation) => ({
463 key: mutation.options.mutationKey,
464 })
465​
466 function Page() {
467 const result = useMutationState({
468 filters: inputs === 'inline' ? { ...filters } : filters,
469 select: inputs === 'inline' ? (mutation) => select(mutation) : select,
470 })
471 React.useEffect(() => {
472 onResult(result)
473 }, [result])
474 return <div>result: {JSON.stringify(result)}</div>
475 }
476​
477 const rendered = renderWithClient(queryClient, <Page />)
478 const expected = `result: ${JSON.stringify([{ key }])}`
479 expect(rendered.getByText(expected)).toBeInTheDocument()
480 expect(onResult).toHaveBeenCalledTimes(1)
481​
482 rendered.rerender(<Page />)
483 expect(rendered.getByText(expected)).toBeInTheDocument()
484 expect(onResult).toHaveBeenCalledTimes(1)
485 },
486 )
487​
488 it('should read from a changed custom queryClient', () => {
489 const client1 = new QueryClient()
490 const client2 = new QueryClient()
491 const key1 = queryKey()
492 const key2 = queryKey()
493 client1.getMutationCache().build(client1, { mutationKey: key1 })
494 client2.getMutationCache().build(client2, { mutationKey: key2 })
495 const select = (mutation: Mutation) => mutation.options.mutationKey
496​
497 function Page({ client }: { client: QueryClient }) {
498 const keys = useMutationState({ select }, client)
499 return <div>keys: {JSON.stringify(keys)}</div>
500 }
501​
502 const rendered = render(<Page client={client1} />)
503 expect(
504 rendered.getByText(`keys: ${JSON.stringify([key1])}`),
505 ).toBeInTheDocument()
506​
507 rendered.rerender(<Page client={client2} />)
508 expect(
509 rendered.getByText(`keys: ${JSON.stringify([key2])}`),
510 ).toBeInTheDocument()
511 expect(client1.getMutationCache().hasListeners()).toBe(false)
512 expect(client2.getMutationCache().hasListeners()).toBe(true)
513 })
514​
515 it('should remove successful mutations when the query client is cleared', async () => {
516 const queryClient = new QueryClient()
517​
518 function Page() {
519 const { mutate } = useMutation({
520 mutationFn: () => Promise.resolve('saved'),
521 })
522 const data = useMutationState({
523 filters: { status: 'success' },
524 select: (mutation) => mutation.state.data,
525 })
526​
527 return (
528 <div>
529 <div>data: {JSON.stringify(data)}</div>
530 <button onClick={() => mutate()}>mutate</button>
531 <button onClick={() => queryClient.clear()}>clear</button>
532 </div>
533 )
534 }
535​
536 const rendered = renderWithClient(queryClient, <Page />)
537 fireEvent.click(rendered.getByRole('button', { name: 'mutate' }))
538 await vi.advanceTimersByTimeAsync(1)
539 expect(rendered.getByText('data: ["saved"]')).toBeInTheDocument()
540​
541 fireEvent.click(rendered.getByRole('button', { name: 'clear' }))
542 await vi.advanceTimersByTimeAsync(1)
543 expect(queryClient.getMutationCache().getAll()).toStrictEqual([])
544 expect(rendered.getByText('data: []')).toBeInTheDocument()
545 })
546​
547 it('should return variables after calling mutate', async () => {
548 const queryClient = new QueryClient()
549 const mutationKey = ['mutation']
550​
551 function Variables() {
552 const variables = useMutationState({
553 filters: { mutationKey, status: 'pending' },
554 select: (mutation) => mutation.state.variables,
555 })
556​
557 return <div>variables: {JSON.stringify(variables)}</div>
558 }
559​
560 function Mutate() {
561 const { mutate, data } = useMutation({
562 mutationKey,
563 mutationFn: (input: number) => sleep(150).then(() => `data${input}`),
564 })
565​
566 return (
567 <div>
568 data: {data ?? 'null'}
569 <button onClick={() => mutate(1)}>mutate</button>
570 </div>
571 )
572 }
573​
574 function Page() {
575 return (
576 <div>
577 <Variables />
578 <Mutate />
579 </div>
580 )
581 }
582​
583 const rendered = renderWithClient(queryClient, <Page />)
584​
585 expect(rendered.getByText('data: null')).toBeInTheDocument()
586 expect(rendered.getByText('variables: []')).toBeInTheDocument()
587​
588 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
589 await vi.advanceTimersByTimeAsync(1)
590 expect(rendered.getByText('variables: [1]')).toBeInTheDocument()
591​
592 await vi.advanceTimersByTimeAsync(150)
593 expect(rendered.getByText('data: data1')).toBeInTheDocument()
594 expect(rendered.getByText('variables: []')).toBeInTheDocument()
595 })
596})