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 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 = queryKey()
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.length).toBe(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.length).toBe(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 = queryKey()
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 consoleErrorMock.mockRestore()
115 })
116β
117 it('should log an error when skipToken is used in development environment', () => {
118 const envCopy = process.env.NODE_ENV
119 process.env.NODE_ENV = 'development'
120β
121 const consoleErrorMock = vi
122 .spyOn(console, 'error')
123 .mockImplementation(() => undefined)
124 const key = queryKey()
125β
126 function Page() {
127 useSuspenseInfiniteQuery({
128 queryKey: key,
129 queryFn: skipToken as any,
130 initialPageParam: 1,
131 getNextPageParam: () => 1,
132 })
133β
134 return null
135 }
136β
137 renderWithClient(
138 queryClient,
139 <React.Suspense fallback="Loading...">
140 <Page />
141 </React.Suspense>,
142 )
143β
144 expect(consoleErrorMock).toHaveBeenCalledWith(
145 'skipToken is not allowed for useSuspenseInfiniteQuery',
146 )
147β
148 consoleErrorMock.mockRestore()
149 process.env.NODE_ENV = envCopy
150 })
151β
152 it('should not log an error when skipToken is used in production environment', () => {
153 const envCopy = process.env.NODE_ENV
154 process.env.NODE_ENV = 'production'
155β
156 const consoleErrorMock = vi
157 .spyOn(console, 'error')
158 .mockImplementation(() => undefined)
159 const key = queryKey()
160β
161 function Page() {
162 useSuspenseInfiniteQuery({
163 queryKey: key,
164 queryFn: skipToken as any,
165 initialPageParam: 1,
166 getNextPageParam: () => 1,
167 })
168β
169 return null
170 }
171β
172 renderWithClient(
173 queryClient,
174 <React.Suspense fallback="Loading...">
175 <Page />
176 </React.Suspense>,
177 )
178β
179 expect(consoleErrorMock).not.toHaveBeenCalled()
180β
181 consoleErrorMock.mockRestore()
182 process.env.NODE_ENV = envCopy
183 })
184β
185 it('should still suspense if queryClient has placeholderData config', async () => {
186 const key = queryKey()
187 const queryClientWithPlaceholder = new QueryClient({
188 defaultOptions: {
189 queries: {
190 placeholderData: (previousData: any) => previousData,
191 },
192 },
193 })
194 const states: Array<UseSuspenseInfiniteQueryResult<InfiniteData<number>>> =
195 []
196β
197 let count = 0
198β
199 function Page() {
200 const [stateKey, setStateKey] = React.useState(key)
201β
202 const state = useSuspenseInfiniteQuery({
203 queryKey: stateKey,
204 queryFn: () => sleep(10).then(() => ++count),
205 initialPageParam: 1,
206 getNextPageParam: () => undefined,
207 })
208β
209 states.push(state)
210β
211 return (
212 <div>
213 <button aria-label="toggle" onClick={() => setStateKey(queryKey())} />
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})