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

useSuspenseInfiniteQuery.test.tsx

235 lines6.1 KB

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})