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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5import {
6 QueryCache,
7 QueryClient,
8 skipToken,
9 useSuspenseInfiniteQuery,
10} from '..'
11import { renderWithClient } from './utils'
12import type { InfiniteData, UseSuspenseInfiniteQueryResult } from '..'
13β
14describe('useSuspenseInfiniteQuery', () => {
15 let queryCache: QueryCache
16 let queryClient: QueryClient
17β
18 beforeEach(() => {
19 vi.useFakeTimers()
20 queryCache = new QueryCache()
21 queryClient = new QueryClient({ queryCache })
22 })
23β
24 afterEach(() => {
25 queryClient.clear()
26 vi.useRealTimers()
27 })
28β
29 it('should return the correct states for a successful infinite query', async () => {
30 const key = createKey()
31 const states: Array<UseSuspenseInfiniteQueryResult<InfiniteData<number>>> =
32 []
33β
34 function Page() {
35 const [multiplier, setMultiplier] = React.useState(1)
36 const state = useSuspenseInfiniteQuery({
37 queryKey: [`${key}_${multiplier}`],
38 queryFn: ({ pageParam }) =>
39 sleep(10).then(() => pageParam * multiplier),
40 initialPageParam: 1,
41 getNextPageParam: (lastPage) => lastPage + 1,
42 })
43β
44 states.push(state)
45β
46 return (
47 <div>
48 <button onClick={() => setMultiplier(2)}>next</button>
49 data: {state.data?.pages.join(',')}
50 </div>
51 )
52 }
53β
54 const rendered = renderWithClient(
55 queryClient,
56 <React.Suspense fallback="loading">
57 <Page />
58 </React.Suspense>,
59 )
60β
61 expect(rendered.getByText('loading')).toBeInTheDocument()
62 await act(() => vi.advanceTimersByTimeAsync(10))
63 expect(rendered.getByText('data: 1')).toBeInTheDocument()
64β
65 expect(states).toHaveLength(1)
66 expect(states[0]).toMatchObject({
67 data: { pages: [1], pageParams: [1] },
68 status: 'success',
69 })
70β
71 fireEvent.click(rendered.getByText('next'))
72 expect(rendered.getByText('loading')).toBeInTheDocument()
73 await act(() => vi.advanceTimersByTimeAsync(10))
74 expect(rendered.getByText('data: 2')).toBeInTheDocument()
75β
76 expect(states).toHaveLength(2)
77 expect(states[1]).toMatchObject({
78 data: { pages: [2], pageParams: [1] },
79 status: 'success',
80 })
81 })
82β
83 it('should log an error when skipToken is passed as queryFn', () => {
84 const consoleErrorMock = vi
85 .spyOn(console, 'error')
86 .mockImplementation(() => {})
87 const key = createKey()
88β
89 function Page() {
90 useSuspenseInfiniteQuery({
91 queryKey: key,
92 initialPageParam: 1,
93 getNextPageParam: () => 1,
94 // @ts-expect-error
95 queryFn: Math.random() >= 0 ? skipToken : () => Promise.resolve(5),
96 })
97β
98 return null
99 }
100β
101 function App() {
102 return (
103 <React.Suspense fallback="Loading...">
104 <Page />
105 </React.Suspense>
106 )
107 }
108β
109 renderWithClient(queryClient, <App />)
110β
111 expect(consoleErrorMock).toHaveBeenCalledWith(
112 'skipToken is not allowed for useSuspenseInfiniteQuery',
113 )
114 })
115β
116 it('should log an error when skipToken is used in development environment', () => {
117 const envCopy = process.env.NODE_ENV
118 process.env.NODE_ENV = 'development'
119β
120 const consoleErrorMock = vi
121 .spyOn(console, 'error')
122 .mockReturnValue(undefined)
123 const key = createKey()
124β
125 function Page() {
126 useSuspenseInfiniteQuery({
127 queryKey: key,
128 queryFn: skipToken as any,
129 initialPageParam: 1,
130 getNextPageParam: () => 1,
131 })
132β
133 return null
134 }
135β
136 renderWithClient(
137 queryClient,
138 <React.Suspense fallback="Loading...">
139 <Page />
140 </React.Suspense>,
141 )
142β
143 expect(consoleErrorMock).toHaveBeenCalledWith(
144 'skipToken is not allowed for useSuspenseInfiniteQuery',
145 )
146β
147 process.env.NODE_ENV = envCopy
148 })
149β
150 it('should not log an error when skipToken is used in production environment', () => {
151 const envCopy = process.env.NODE_ENV
152 process.env.NODE_ENV = 'production'
153β
154 const consoleErrorMock = vi
155 .spyOn(console, 'error')
156 .mockReturnValue(undefined)
157 const key = createKey()
158β
159 function Page() {
160 useSuspenseInfiniteQuery({
161 queryKey: key,
162 queryFn: skipToken as any,
163 initialPageParam: 1,
164 getNextPageParam: () => 1,
165 })
166β
167 return null
168 }
169β
170 renderWithClient(
171 queryClient,
172 <React.Suspense fallback="Loading...">
173 <Page />
174 </React.Suspense>,
175 )
176β
177 expect(consoleErrorMock).not.toHaveBeenCalled()
178β
179 process.env.NODE_ENV = envCopy
180 })
181β
182 it('should still suspense if queryClient has placeholderData config', async () => {
183 const key = createKey()
184 const queryClientWithPlaceholder = new QueryClient({
185 defaultOptions: {
186 queries: {
187 placeholderData: (previousData: any) => previousData,
188 },
189 },
190 })
191 const states: Array<UseSuspenseInfiniteQueryResult<InfiniteData<number>>> =
192 []
193β
194 let count = 0
195β
196 function Page() {
197 const [stateKey, setStateKey] = React.useState(key)
198β
199 const state = useSuspenseInfiniteQuery({
200 queryKey: stateKey,
201 queryFn: () => sleep(10).then(() => ++count),
202 initialPageParam: 1,
203 getNextPageParam: () => undefined,
204 })
205β
206 states.push(state)
207β
208 return (
209 <div>
210 <button
211 aria-label="toggle"
212 onClick={() => setStateKey(createKey())}
213 />
214 data: {String(state.data?.pages.join(','))}
215 </div>
216 )
217 }
218β
219 const rendered = renderWithClient(
220 queryClientWithPlaceholder,
221 <React.Suspense fallback="loading">
222 <Page />
223 </React.Suspense>,
224 )
225β
226 expect(rendered.getByText('loading')).toBeInTheDocument()
227 await act(() => vi.advanceTimersByTimeAsync(10))
228 expect(rendered.getByText('data: 1')).toBeInTheDocument()
229β
230 fireEvent.click(rendered.getByLabelText('toggle'))
231 expect(rendered.getByText('loading')).toBeInTheDocument()
232 await act(() => vi.advanceTimersByTimeAsync(10))
233 expect(rendered.getByText('data: 2')).toBeInTheDocument()
234 })
235})