Open History to see the last commit
1import { createKey, sleep } from '@tanstack/query-test-utils'
2import { fireEvent } from '@testing-library/preact'
3import { Suspense } from 'preact/compat'
4import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5β
6import {
7 QueryCache,
8 QueryClient,
9 noop,
10 usePrefetchInfiniteQuery,
11 useSuspenseInfiniteQuery,
12} from '..'
13import { renderWithClient } from './utils'
14import type { JSX, VNode } from 'preact'
15β
16describe('usePrefetchInfiniteQuery', () => {
17 let queryCache: QueryCache
18 let queryClient: QueryClient
19β
20 beforeEach(() => {
21 vi.useFakeTimers()
22 queryCache = new QueryCache()
23 queryClient = new QueryClient({ queryCache })
24 })
25β
26 afterEach(() => {
27 queryClient.clear()
28 Fallback.mockClear()
29 vi.useRealTimers()
30 })
31β
32 const Fallback = vi
33 .fn<() => JSX.Element>()
34 .mockReturnValue(<div>Loading...</div>)
35β
36 it('should prefetch an infinite query if query state does not exist', async () => {
37 const data = [
38 'Do you fetch on render?',
39 'Or do you render as you fetch?',
40 'Either way, Tanstack Query helps you!',
41 ]
42β
43 const queryOpts = {
44 queryKey: createKey(),
45 queryFn: vi
46 .fn<(context: { pageParam: number }) => Promise<string>>()
47 .mockImplementation(({ pageParam }) =>
48 sleep(10).then(() => data[pageParam]!),
49 ),
50 initialPageParam: 0,
51 getNextPageParam: (_lastPage: string, allPages: Array<string>) =>
52 allPages.length < data.length ? allPages.length : undefined,
53 }
54β
55 function Page() {
56 const state = useSuspenseInfiniteQuery(queryOpts)
57β
58 return (
59 <div>
60 {state.data.pages.map((page) => (
61 <div key={page}>data: {page}</div>
62 ))}
63 <button onClick={() => state.fetchNextPage()}>Next Page</button>
64 </div>
65 )
66 }
67β
68 function App() {
69 usePrefetchInfiniteQuery({ ...queryOpts, pages: data.length })
70β
71 return (
72 <Suspense fallback={<Fallback />}>
73 <Page />
74 </Suspense>
75 )
76 }
77β
78 const rendered = renderWithClient(queryClient, <App />)
79β
80 await vi.advanceTimersByTimeAsync(30)
81 rendered.getByText('data: Do you fetch on render?')
82β
83 fireEvent.click(rendered.getByText('Next Page'))
84 expect(
85 rendered.getByText('data: Or do you render as you fetch?'),
86 ).toBeInTheDocument()
87β
88 fireEvent.click(rendered.getByText('Next Page'))
89 expect(
90 rendered.getByText('data: Either way, Tanstack Query helps you!'),
91 ).toBeInTheDocument()
92 expect(Fallback).toHaveBeenCalledTimes(1)
93 expect(queryOpts.queryFn).toHaveBeenCalledTimes(3)
94 })
95β
96 it('should not display fallback if the query cache is already populated', async () => {
97 const data = [
98 'Prefetch rocks!',
99 'No waterfalls, boy!',
100 'Tanstack Query #ftw',
101 ]
102β
103 const queryOpts = {
104 queryKey: createKey(),
105 queryFn: vi
106 .fn<(context: { pageParam: number }) => Promise<string>>()
107 .mockImplementation(({ pageParam }) =>
108 sleep(10).then(() => data[pageParam]!),
109 ),
110 initialPageParam: 0,
111 getNextPageParam: (_lastPage: string, allPages: Array<string>) =>
112 allPages.length < data.length ? allPages.length : undefined,
113 }
114β
115 void queryClient.infiniteQuery({ ...queryOpts, pages: 3 }).catch(noop)
116 await vi.advanceTimersByTimeAsync(30)
117 queryOpts.queryFn.mockClear()
118β
119 function Page() {
120 const state = useSuspenseInfiniteQuery(queryOpts)
121β
122 return (
123 <div>
124 {state.data.pages.map((page) => (
125 <div key={page}>data: {page}</div>
126 ))}
127 <button onClick={() => state.fetchNextPage()}>Next Page</button>
128 </div>
129 )
130 }
131β
132 function App() {
133 usePrefetchInfiniteQuery(queryOpts)
134β
135 return (
136 <Suspense fallback={<Fallback />}>
137 <Page />
138 </Suspense>
139 )
140 }
141β
142 const rendered = renderWithClient(queryClient, <App />)
143β
144 expect(rendered.getByText('data: Prefetch rocks!')).toBeInTheDocument()
145β
146 fireEvent.click(rendered.getByText('Next Page'))
147 expect(rendered.getByText('data: No waterfalls, boy!')).toBeInTheDocument()
148β
149 fireEvent.click(rendered.getByText('Next Page'))
150 expect(rendered.getByText('data: Tanstack Query #ftw')).toBeInTheDocument()
151 expect(queryOpts.queryFn).not.toHaveBeenCalled()
152 expect(Fallback).not.toHaveBeenCalled()
153 })
154β
155 it('should not create an endless loop when using inside a suspense boundary', async () => {
156 const data = ['Infinite Page 1', 'Infinite Page 2', 'Infinite Page 3']
157β
158 const queryOpts = {
159 queryKey: createKey(),
160 queryFn: vi
161 .fn<(context: { pageParam: number }) => Promise<string>>()
162 .mockImplementation(({ pageParam }) =>
163 sleep(10).then(() => data[pageParam]!),
164 ),
165 initialPageParam: 0,
166 // always reports another page available, to guard against an endless
167 // auto-advance loop rather than a bounded pagination sequence
168 getNextPageParam: (_lastPage: string, allPages: Array<string>) =>
169 allPages.length,
170 }
171β
172 function Prefetch({ children }: { children: VNode }) {
173 usePrefetchInfiniteQuery(queryOpts)
174 return <>{children}</>
175 }
176β
177 function Page() {
178 const state = useSuspenseInfiniteQuery(queryOpts)
179β
180 return (
181 <div>
182 {state.data.pages.map((page) => (
183 <div key={page}>data: {page}</div>
184 ))}
185 <button onClick={() => state.fetchNextPage()}>Next Page</button>
186 </div>
187 )
188 }
189β
190 function App() {
191 return (
192 <Suspense fallback={<></>}>
193 <Prefetch>
194 <Page />
195 </Prefetch>
196 </Suspense>
197 )
198 }
199β
200 const rendered = renderWithClient(queryClient, <App />)
201β
202 await vi.advanceTimersByTimeAsync(10)
203 rendered.getByText('data: Infinite Page 1')
204β
205 fireEvent.click(rendered.getByText('Next Page'))
206 await vi.advanceTimersByTimeAsync(11)
207 expect(rendered.getByText('data: Infinite Page 2')).toBeInTheDocument()
208β
209 fireEvent.click(rendered.getByText('Next Page'))
210 await vi.advanceTimersByTimeAsync(11)
211 expect(rendered.getByText('data: Infinite Page 3')).toBeInTheDocument()
212 expect(queryOpts.queryFn).toHaveBeenCalledTimes(3)
213 })
214})