Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { act, fireEvent } from '@testing-library/react'
3import * as React from 'react'
4import { queryKey, sleep } from '@tanstack/query-test-utils'
5import {
6 QueryCache,
7 QueryClient,
8 keepPreviousData,
9 skipToken,
10 useSuspenseInfiniteQuery,
11} from '..'
12import { renderWithSuspense } from './utils'
13import type { InfiniteData, UseSuspenseInfiniteQueryResult } from '..'
14β
15describe('useSuspenseInfiniteQuery', () => {
16 let queryCache: QueryCache
17 let queryClient: QueryClient
18β
19 beforeEach(() => {
20 vi.useFakeTimers()
21 queryCache = new QueryCache()
22 queryClient = new QueryClient({ queryCache })
23 })
24β
25 afterEach(() => {
26 queryClient.clear()
27 vi.useRealTimers()
28 })
29β
30 it('should return the correct states for a successful infinite query', async () => {
31 const key = queryKey()
32 const states: Array<UseSuspenseInfiniteQueryResult<InfiniteData<number>>> =
33 []
34β
35 function Page() {
36 const [multiplier, setMultiplier] = React.useState(1)
37 const state = useSuspenseInfiniteQuery({
38 queryKey: [`${key}_${multiplier}`],
39 queryFn: ({ pageParam }) =>
40 sleep(10).then(() => pageParam * multiplier),
41 initialPageParam: 1,
42 getNextPageParam: (lastPage) => lastPage + 1,
43 })
44β
45 states.push(state)
46β
47 return (
48 <div>
49 <button onClick={() => setMultiplier(2)}>next</button>
50 data: {state.data?.pages.join(',')}
51 </div>
52 )
53 }
54β
55 const rendered = await renderWithSuspense(queryClient, <Page />)
56β
57 expect(rendered.getByText('loading')).toBeInTheDocument()
58 await act(() => vi.advanceTimersByTimeAsync(10))
59 expect(rendered.getByText('data: 1')).toBeInTheDocument()
60β
61 expect(states.length).toBe(1)
62 expect(states[0]).toMatchObject({
63 data: { pages: [1], pageParams: [1] },
64 status: 'success',
65 })
66β
67 await act(async () => {
68 fireEvent.click(rendered.getByText('next'))
69 })
70 expect(rendered.getByText('loading')).toBeInTheDocument()
71 await act(() => vi.advanceTimersByTimeAsync(10))
72 expect(rendered.getByText('data: 2')).toBeInTheDocument()
73β
74 expect(states.length).toBe(2)
75 expect(states[1]).toMatchObject({
76 data: { pages: [2], pageParams: [1] },
77 status: 'success',
78 })
79 })
80β
81 it('should log an error when skipToken is passed as queryFn', async () => {
82 const consoleErrorSpy = vi
83 .spyOn(console, 'error')
84 .mockImplementation(() => {})
85 const key = queryKey()
86β
87 function Page() {
88 useSuspenseInfiniteQuery({
89 queryKey: key,
90 initialPageParam: 1,
91 getNextPageParam: () => 1,
92 // @ts-expect-error
93 // eslint-disable-next-line react-hooks/purity
94 queryFn: Math.random() >= 0 ? skipToken : () => Promise.resolve(5),
95 })
96β
97 return null
98 }
99β
100 function App() {
101 return (
102 <React.Suspense fallback="Loading...">
103 <Page />
104 </React.Suspense>
105 )
106 }
107β
108 await renderWithSuspense(queryClient, <App />)
109β
110 expect(consoleErrorSpy).toHaveBeenCalledWith(
111 'skipToken is not allowed for useSuspenseInfiniteQuery',
112 )
113 consoleErrorSpy.mockRestore()
114 })
115β
116 it('should log an error when skipToken is used in development environment', async () => {
117 const envCopy = process.env.NODE_ENV
118 process.env.NODE_ENV = 'development'
119β
120 const consoleErrorSpy = vi
121 .spyOn(console, 'error')
122 .mockImplementation(() => undefined)
123 const key = queryKey()
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 await renderWithSuspense(queryClient, <Page />)
137β
138 expect(consoleErrorSpy).toHaveBeenCalledWith(
139 'skipToken is not allowed for useSuspenseInfiniteQuery',
140 )
141β
142 consoleErrorSpy.mockRestore()
143 process.env.NODE_ENV = envCopy
144 })
145β
146 it('should not log an error when skipToken is used in production environment', async () => {
147 const envCopy = process.env.NODE_ENV
148 process.env.NODE_ENV = 'production'
149β
150 const consoleErrorSpy = vi
151 .spyOn(console, 'error')
152 .mockImplementation(() => undefined)
153 const key = queryKey()
154β
155 function Page() {
156 useSuspenseInfiniteQuery({
157 queryKey: key,
158 queryFn: skipToken as any,
159 initialPageParam: 1,
160 getNextPageParam: () => 1,
161 })
162β
163 return null
164 }
165β
166 await renderWithSuspense(queryClient, <Page />)
167β
168 expect(consoleErrorSpy).not.toHaveBeenCalled()
169β
170 consoleErrorSpy.mockRestore()
171 process.env.NODE_ENV = envCopy
172 })
173β
174 it('should use static placeholderData without suspending', async () => {
175 const key = queryKey()
176 const queryFn = vi.fn(() => sleep(10).then(() => 1))
177 const states: Array<UseSuspenseInfiniteQueryResult<InfiniteData<number>>> =
178 []
179β
180 function Page() {
181 const state = useSuspenseInfiniteQuery({
182 queryKey: key,
183 queryFn,
184 initialPageParam: 1,
185 getNextPageParam: () => undefined,
186 placeholderData: { pages: [0], pageParams: [1] },
187 })
188β
189 states.push(state)
190 return <div>data: {state.data.pages.join(',')}</div>
191 }
192β
193 const rendered = await renderWithSuspense(queryClient, <Page />)
194β
195 expect(rendered.queryByText('loading')).not.toBeInTheDocument()
196 expect(rendered.getByText('data: 0')).toBeInTheDocument()
197 expect(states.at(-1)?.isPlaceholderData).toBe(true)
198 expect(queryFn).toHaveBeenCalledTimes(1)
199β
200 await act(() => vi.advanceTimersByTimeAsync(11))
201β
202 expect(rendered.getByText('data: 1')).toBeInTheDocument()
203 expect(states.at(-1)?.isPlaceholderData).toBe(false)
204 expect(queryFn).toHaveBeenCalledTimes(1)
205 })
206β
207 it('should use keepPreviousData from queryClient defaults', async () => {
208 const key = queryKey()
209 const queryClientWithPlaceholder = new QueryClient({
210 defaultOptions: {
211 queries: {
212 placeholderData: keepPreviousData,
213 },
214 },
215 })
216 const states: Array<UseSuspenseInfiniteQueryResult<InfiniteData<number>>> =
217 []
218β
219 let count = 0
220β
221 function Page() {
222 const [stateKey, setStateKey] = React.useState(key)
223β
224 const state = useSuspenseInfiniteQuery({
225 queryKey: stateKey,
226 queryFn: () => sleep(10).then(() => ++count),
227 initialPageParam: 1,
228 getNextPageParam: () => undefined,
229 })
230β
231 states.push(state)
232β
233 return (
234 <div>
235 <button aria-label="toggle" onClick={() => setStateKey(queryKey())} />
236 data: {String(state.data?.pages.join(','))}
237 </div>
238 )
239 }
240β
241 const rendered = await renderWithSuspense(
242 queryClientWithPlaceholder,
243 <Page />,
244 )
245β
246 expect(rendered.getByText('loading')).toBeInTheDocument()
247 await act(() => vi.advanceTimersByTimeAsync(11))
248 expect(rendered.getByText('data: 1')).toBeInTheDocument()
249β
250 await act(async () => {
251 fireEvent.click(rendered.getByLabelText('toggle'))
252 })
253 expect(rendered.queryByText('loading')).not.toBeInTheDocument()
254 expect(rendered.getByText('data: 1')).toBeInTheDocument()
255 expect(states.at(-1)).toMatchObject({
256 data: { pages: [1], pageParams: [1] },
257 isPlaceholderData: true,
258 isFetching: true,
259 })
260 await act(() => vi.advanceTimersByTimeAsync(11))
261 expect(rendered.getByText('data: 2')).toBeInTheDocument()
262 expect(states.at(-1)).toMatchObject({
263 data: { pages: [2], pageParams: [1] },
264 isPlaceholderData: false,
265 isFetching: false,
266 })
267 })
268β
269 it('should start a keepPreviousData fetch during a transition', async () => {
270 const key = queryKey()
271 const queryFn = vi.fn((count: number) => sleep(10).then(() => count))
272β
273 function Page() {
274 const [count, setCount] = React.useState(0)
275 const state = useSuspenseInfiniteQuery({
276 queryKey: [...key, count],
277 queryFn: () => queryFn(count),
278 initialPageParam: 1,
279 getNextPageParam: () => undefined,
280 placeholderData: keepPreviousData,
281 })
282β
283 return (
284 <div>
285 <button
286 onClick={() =>
287 React.startTransition(() => setCount((value) => value + 1))
288 }
289 >
290 next
291 </button>
292 <div>data: {state.data.pages.join(',')}</div>
293 <div>placeholder: {String(state.isPlaceholderData)}</div>
294 </div>
295 )
296 }
297β
298 const rendered = await renderWithSuspense(queryClient, <Page />)
299β
300 await act(() => vi.advanceTimersByTimeAsync(10))
301 expect(rendered.getByText('data: 0')).toBeInTheDocument()
302β
303 await act(async () => {
304 fireEvent.click(rendered.getByText('next'))
305 })
306β
307 expect(rendered.getByText('data: 0')).toBeInTheDocument()
308 expect(rendered.getByText('placeholder: true')).toBeInTheDocument()
309 expect(rendered.queryByText('loading')).not.toBeInTheDocument()
310 expect(queryFn).toHaveBeenCalledTimes(2)
311β
312 await act(() => vi.advanceTimersByTimeAsync(11))
313 expect(rendered.getByText('data: 1')).toBeInTheDocument()
314 expect(rendered.getByText('placeholder: false')).toBeInTheDocument()
315 expect(queryFn).toHaveBeenCalledTimes(2)
316 })
317})