Open History to see the last commit
1import { createKey, sleep } from '@tanstack/query-test-utils'
2import { act, fireEvent } from '@testing-library/react'
3import * as React from 'react'
4import { Suspense, startTransition, useDeferredValue } from 'react'
5import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
6import { QueryClient, useSuspenseQuery } from '..'
7import { renderWithClient } from './utils'
8β
9describe('react transitions', () => {
10 let queryClient: QueryClient
11β
12 beforeEach(() => {
13 vi.useFakeTimers()
14 queryClient = new QueryClient()
15 })
16β
17 afterEach(() => {
18 queryClient.clear()
19 vi.useRealTimers()
20 })
21β
22 it('should keep values of old key around with useDeferredValue', async () => {
23 const key = createKey()
24β
25 function Page() {
26 const [count, setCount] = React.useState(0)
27 const deferredCount = useDeferredValue(count)
28 const query = useSuspenseQuery({
29 queryKey: [key, deferredCount],
30 queryFn: () => sleep(10).then(() => 'test' + deferredCount),
31 })
32β
33 return (
34 <div>
35 <button onClick={() => setCount((c) => c + 1)}>increment</button>
36 <div>data: {query.data}</div>
37 </div>
38 )
39 }
40β
41 const rendered = await renderWithClient(
42 queryClient,
43 <Suspense fallback="loading">
44 <Page />
45 </Suspense>,
46 )
47β
48 expect(rendered.getByText('loading')).toBeInTheDocument()
49 await act(() => vi.advanceTimersByTimeAsync(10))
50 expect(rendered.getByText('data: test0')).toBeInTheDocument()
51β
52 fireEvent.click(rendered.getByRole('button', { name: 'increment' }))
53 expect(rendered.getByText('data: test0')).toBeVisible()
54 expect(rendered.queryByText('loading')).not.toBeInTheDocument()
55 await act(() => vi.advanceTimersByTimeAsync(10))
56 expect(rendered.getByText('data: test1')).toBeInTheDocument()
57 })
58β
59 it('should keep values of old key around with startTransition', async () => {
60 const key = createKey()
61β
62 function Page() {
63 const [count, setCount] = React.useState(0)
64 const query = useSuspenseQuery({
65 queryKey: [key, count],
66 queryFn: () => sleep(10).then(() => 'test' + count),
67 })
68β
69 return (
70 <div>
71 <button onClick={() => startTransition(() => setCount((c) => c + 1))}>
72 increment
73 </button>
74 <div>data: {query.data}</div>
75 </div>
76 )
77 }
78β
79 const rendered = await renderWithClient(
80 queryClient,
81 <Suspense fallback="loading">
82 <Page />
83 </Suspense>,
84 )
85β
86 expect(rendered.getByText('loading')).toBeInTheDocument()
87 await act(() => vi.advanceTimersByTimeAsync(10))
88 expect(rendered.getByText('data: test0')).toBeInTheDocument()
89β
90 fireEvent.click(rendered.getByRole('button', { name: 'increment' }))
91 expect(rendered.getByText('data: test0')).toBeVisible()
92 expect(rendered.queryByText('loading')).not.toBeInTheDocument()
93 await act(() => vi.advanceTimersByTimeAsync(10))
94 expect(rendered.getByText('data: test1')).toBeInTheDocument()
95 })
96})