-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathusePrefetchQuery.test.tsx
More file actions
294 lines (245 loc) · 8.14 KB
/
usePrefetchQuery.test.tsx
File metadata and controls
294 lines (245 loc) · 8.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import { queryKey, sleep } from '@tanstack/query-test-utils'
import { act, fireEvent } from '@testing-library/preact'
import type { VNode } from 'preact'
import { Suspense } from 'preact/compat'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
QueryCache,
QueryClient,
usePrefetchQuery,
useQueryErrorResetBoundary,
useSuspenseQuery,
} from '..'
import type { UseSuspenseQueryOptions } from '..'
import { ErrorBoundary } from './ErrorBoundary'
import { renderWithClient } from './utils'
const generateQueryFn = (data: string) =>
vi
.fn<(...args: Array<any>) => Promise<string>>()
.mockImplementation(async () => {
await sleep(10)
return data
})
describe('usePrefetchQuery', () => {
let queryCache: QueryCache
let queryClient: QueryClient
beforeEach(() => {
vi.useFakeTimers()
queryCache = new QueryCache()
queryClient = new QueryClient({ queryCache })
})
afterEach(() => {
vi.useRealTimers()
queryClient.clear()
})
function Suspended<TData = unknown>(props: {
queryOpts: UseSuspenseQueryOptions<TData, Error, TData, Array<string>>
children?: VNode
}) {
const state = useSuspenseQuery(props.queryOpts)
return (
<div>
<div>data: {String(state.data)}</div>
{props.children}
</div>
)
}
it('should prefetch query if query state does not exist', async () => {
const queryOpts = {
queryKey: queryKey(),
queryFn: generateQueryFn('prefetchQuery'),
}
const componentQueryOpts = {
...queryOpts,
queryFn: generateQueryFn('useSuspenseQuery'),
}
function App() {
usePrefetchQuery(queryOpts)
return (
<Suspense fallback="Loading...">
<Suspended queryOpts={componentQueryOpts} />
</Suspense>
)
}
const rendered = renderWithClient(queryClient, <App />)
await vi.advanceTimersByTimeAsync(10)
expect(rendered.getByText('data: prefetchQuery')).toBeInTheDocument()
expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
})
it('should not prefetch query if query state exists', async () => {
const queryOpts = {
queryKey: queryKey(),
queryFn: generateQueryFn('The usePrefetchQuery hook is smart!'),
}
function App() {
usePrefetchQuery(queryOpts)
return (
<Suspense fallback="Loading...">
<Suspended queryOpts={queryOpts} />
</Suspense>
)
}
queryClient.fetchQuery(queryOpts)
await vi.advanceTimersByTimeAsync(10)
queryOpts.queryFn.mockClear()
const rendered = renderWithClient(queryClient, <App />)
expect(rendered.queryByText('fetching: true')).not.toBeInTheDocument()
expect(
rendered.getByText('data: The usePrefetchQuery hook is smart!'),
).toBeInTheDocument()
expect(queryOpts.queryFn).not.toHaveBeenCalled()
})
it('should let errors fall through and not refetch failed queries', async () => {
const consoleMock = vi.spyOn(console, 'error')
consoleMock.mockImplementation(() => undefined)
const queryFn = generateQueryFn('Not an error')
const queryOpts = {
queryKey: queryKey(),
queryFn,
}
queryFn.mockImplementationOnce(async () => {
await sleep(10)
throw new Error('Oops! Server error!')
})
function App() {
usePrefetchQuery(queryOpts)
return (
<ErrorBoundary fallbackRender={() => <div>Oops!</div>}>
<Suspense fallback="Loading...">
<Suspended queryOpts={queryOpts} />
</Suspense>
</ErrorBoundary>
)
}
queryClient.prefetchQuery(queryOpts)
await vi.advanceTimersByTimeAsync(10)
queryFn.mockClear()
const rendered = renderWithClient(queryClient, <App />)
expect(rendered.getByText('Oops!')).toBeInTheDocument()
expect(rendered.queryByText('data: Not an error')).not.toBeInTheDocument()
expect(queryOpts.queryFn).not.toHaveBeenCalled()
consoleMock.mockRestore()
})
it('should not create an endless loop when using inside a suspense boundary', async () => {
const queryFn = generateQueryFn('prefetchedQuery')
const queryOpts = {
queryKey: queryKey(),
queryFn,
}
function Prefetch({ children }: { children: VNode }) {
usePrefetchQuery(queryOpts)
return <>{children}</>
}
function App() {
return (
<Suspense fallback={<></>}>
<Prefetch>
<Suspended queryOpts={queryOpts} />
</Prefetch>
</Suspense>
)
}
const rendered = renderWithClient(queryClient, <App />)
await vi.advanceTimersByTimeAsync(10)
expect(rendered.getByText('data: prefetchedQuery')).toBeInTheDocument()
expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
})
it('should be able to recover from errors and try fetching again', async () => {
const consoleMock = vi.spyOn(console, 'error')
consoleMock.mockImplementation(() => undefined)
const queryFn = generateQueryFn('This is fine :dog: :fire:')
const queryOpts = {
queryKey: queryKey(),
queryFn,
}
queryFn.mockImplementationOnce(async () => {
await sleep(10)
throw new Error('Oops! Server error!')
})
function App() {
const { reset } = useQueryErrorResetBoundary()
usePrefetchQuery(queryOpts)
return (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
<div>Oops!</div>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)}
>
<Suspense fallback="Loading...">
<Suspended queryOpts={queryOpts} />
</Suspense>
</ErrorBoundary>
)
}
queryClient.prefetchQuery(queryOpts)
await vi.advanceTimersByTimeAsync(10)
queryFn.mockClear()
const rendered = renderWithClient(queryClient, <App />)
expect(rendered.getByText('Oops!')).toBeInTheDocument()
fireEvent.click(rendered.getByText('Try again'))
await vi.advanceTimersByTimeAsync(10)
expect(
rendered.getByText('data: This is fine :dog: :fire:'),
).toBeInTheDocument()
expect(queryOpts.queryFn).toHaveBeenCalledTimes(1)
consoleMock.mockRestore()
})
it('should not create a suspense waterfall if prefetch is fired', async () => {
const firstQueryOpts = {
queryKey: queryKey(),
queryFn: generateQueryFn('Prefetch is nice!'),
}
const secondQueryOpts = {
queryKey: queryKey(),
queryFn: generateQueryFn('Prefetch is really nice!!'),
}
const thirdQueryOpts = {
queryKey: queryKey(),
queryFn: generateQueryFn('Prefetch does not create waterfalls!!'),
}
const Fallback = vi.fn().mockImplementation(() => <div>Loading...</div>)
function App() {
usePrefetchQuery(firstQueryOpts)
usePrefetchQuery(secondQueryOpts)
usePrefetchQuery(thirdQueryOpts)
return (
<Suspense fallback={<Fallback />}>
<Suspended queryOpts={firstQueryOpts}>
<Suspended queryOpts={secondQueryOpts}>
<Suspended queryOpts={thirdQueryOpts} />
</Suspended>
</Suspended>
</Suspense>
)
}
const rendered = renderWithClient(queryClient, <App />)
expect(
queryClient.getQueryState(firstQueryOpts.queryKey)?.fetchStatus,
).toBe('fetching')
expect(
queryClient.getQueryState(secondQueryOpts.queryKey)?.fetchStatus,
).toBe('fetching')
expect(
queryClient.getQueryState(thirdQueryOpts.queryKey)?.fetchStatus,
).toBe('fetching')
expect(rendered.getByText('Loading...')).toBeInTheDocument()
await act(async () => {
await vi.advanceTimersByTimeAsync(10)
})
expect(rendered.getByText('data: Prefetch is nice!')).toBeInTheDocument()
expect(
rendered.getByText('data: Prefetch is really nice!!'),
).toBeInTheDocument()
expect(
rendered.getByText('data: Prefetch does not create waterfalls!!'),
).toBeInTheDocument()
expect(Fallback).toHaveBeenCalledTimes(1)
expect(firstQueryOpts.queryFn).toHaveBeenCalledTimes(1)
expect(secondQueryOpts.queryFn).toHaveBeenCalledTimes(1)
expect(thirdQueryOpts.queryFn).toHaveBeenCalledTimes(1)
})
})