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

infinite-and-options.test.ts

582 lines15.6 KB

1import { describe, expect, it } from 'vitest'
2import { QueryClient } from '@tanstack/query-core'
3import type { ReactiveController, ReactiveControllerHost } from 'lit'
4import { QueryClientProvider } from '../QueryClientProvider.js'
5import { createInfiniteQueryController } from '../createInfiniteQueryController.js'
6import { createMutationController } from '../createMutationController.js'
7import { createQueryController } from '../createQueryController.js'
8import { infiniteQueryOptions } from '../infiniteQueryOptions.js'
9import { mutationOptions } from '../mutationOptions.js'
10import { queryOptions } from '../queryOptions.js'
11import {
12 TestControllerHost,
13 TestElementHost,
14 waitFor,
15 waitForMissingQueryClient,
16} from './testHost.js'
17​
18const providerTagName = 'test-query-client-provider-infinite'
19if (!customElements.get(providerTagName)) {
20 customElements.define(providerTagName, QueryClientProvider)
22​
23let explicitInfiniteClient: QueryClient | undefined
24​
25class ContextInfiniteHostElement extends TestElementHost {
26 readonly queryKey = ['context-infinite'] as const
27​
28 readonly infinite = createInfiniteQueryController(
29 this,
30 {
31 queryKey: this.queryKey,
32 initialPageParam: 0,
33 queryFn: async ({ pageParam }) => Number(pageParam),
34 getNextPageParam: (lastPage) => (lastPage < 1 ? lastPage + 1 : undefined),
35 getPreviousPageParam: (firstPage) =>
36 firstPage > -1 ? firstPage - 1 : undefined,
37 retry: false,
38 },
39 explicitInfiniteClient,
40 )
42​
43const contextInfiniteTagName = 'test-context-infinite-host'
44if (!customElements.get(contextInfiniteTagName)) {
45 customElements.define(contextInfiniteTagName, ContextInfiniteHostElement)
47​
48describe('createInfiniteQueryController', () => {
49 it('LC-INF-01: first provider connection resolves from the pre-connect placeholder state', async () => {
50 const consumer = document.createElement(
51 contextInfiniteTagName,
52 ) as ContextInfiniteHostElement
53​
54 expect(consumer.infinite().status).toBe('pending')
55 await expect(consumer.infinite.refetch()).rejects.toThrow(
56 /No QueryClient available/,
57 )
58 await expect(consumer.infinite.fetchNextPage()).rejects.toThrow(
59 /No QueryClient available/,
60 )
61​
62 const client = new QueryClient({
63 defaultOptions: {
64 queries: {
65 retry: false,
66 },
67 },
68 })
69 const provider = document.createElement(
70 providerTagName,
71 ) as QueryClientProvider
72 provider.client = client
73 provider.append(consumer)
74​
75 document.body.append(provider)
76 await provider.updateComplete
77 await consumer.updateComplete
78​
79 await waitFor(() => consumer.infinite().isSuccess)
80 expect(consumer.infinite().data?.pages).toEqual([0])
81​
82 consumer.infinite.destroy()
83 provider.remove()
84 await Promise.resolve()
85 })
86​
87 it('LC-INF-02: explicit client takes precedence over provider context', async () => {
88 const explicitClient = new QueryClient({
89 defaultOptions: {
90 queries: {
91 retry: false,
92 },
93 },
94 })
95 const providerClient = new QueryClient({
96 defaultOptions: {
97 queries: {
98 retry: false,
99 },
100 },
101 })
102 explicitInfiniteClient = explicitClient
103​
104 const provider = document.createElement(
105 providerTagName,
106 ) as QueryClientProvider
107 provider.client = providerClient
108​
109 const consumer = document.createElement(
110 contextInfiniteTagName,
111 ) as ContextInfiniteHostElement
112 provider.append(consumer)
113​
114 document.body.append(provider)
115 await provider.updateComplete
116 await consumer.updateComplete
117​
118 await waitFor(() => consumer.infinite().isSuccess)
119 expect(consumer.infinite().data?.pages).toEqual([0])
120 expect(
121 explicitClient.getQueryCache().find({ queryKey: consumer.queryKey }),
122 ).toBeDefined()
123 expect(
124 providerClient.getQueryCache().find({ queryKey: consumer.queryKey }),
125 ).toBeUndefined()
126​
127 consumer.infinite.destroy()
128 provider.remove()
129 explicitInfiniteClient = undefined
130 await Promise.resolve()
131 })
132​
133 it('M14: supports initial page, fetchNextPage, and fetchPreviousPage', async () => {
134 const client = new QueryClient({
135 defaultOptions: {
136 queries: {
137 retry: false,
138 },
139 },
140 })
141​
142 const host = new TestControllerHost()
143 const infinite = createInfiniteQueryController(
144 host,
145 {
146 queryKey: ['m14', 'infinite'],
147 initialPageParam: 0,
148 queryFn: async ({ pageParam }) => Number(pageParam),
149 getNextPageParam: (lastPage) =>
150 lastPage < 1 ? lastPage + 1 : undefined,
151 getPreviousPageParam: (firstPage) =>
152 firstPage > -1 ? firstPage - 1 : undefined,
153 },
154 client,
155 )
156​
157 host.connect()
158 host.update()
159​
160 await waitFor(() => infinite().isSuccess)
161 expect(infinite().data?.pages).toEqual([0])
162​
163 await infinite.fetchNextPage()
164 await waitFor(() => (infinite().data?.pages.length ?? 0) === 2)
165 expect(infinite().data?.pages).toEqual([0, 1])
166​
167 await infinite.fetchPreviousPage()
168 await waitFor(() => (infinite().data?.pages.length ?? 0) === 3)
169 expect(infinite().data?.pages).toEqual([-1, 0, 1])
170 })
171​
172 it('does not request another update when stable function options refresh during host update', async () => {
173 const client = new QueryClient({
174 defaultOptions: {
175 queries: {
176 retry: false,
177 },
178 },
179 })
180​
181 const host = new TestControllerHost()
182 let callCount = 0
183​
184 const infinite = createInfiniteQueryController(
185 host,
186 () => ({
187 queryKey: ['infinite-controller', 'stable-function-options'],
188 initialPageParam: 0,
189 queryFn: async ({ pageParam }) => {
190 callCount += 1
191 return Number(pageParam)
192 },
193 getNextPageParam: () => undefined,
194 staleTime: Infinity,
195 }),
196 client,
197 )
198​
199 try {
200 host.connect()
201 host.update()
202​
203 await waitFor(() => infinite().isSuccess)
204​
205 host.updatesRequested = 0
206​
207 for (let i = 0; i < 5; i += 1) {
208 host.update()
209 await Promise.resolve()
210 }
211​
212 expect(host.updatesRequested).toBe(0)
213 expect(infinite().data?.pages).toEqual([0])
214 expect(callCount).toBe(1)
215 } finally {
216 infinite.destroy()
217 }
218 })
219​
220 it('does not request an update for refetch-only state changes when only data was read', async () => {
221 const client = new QueryClient({
222 defaultOptions: {
223 queries: {
224 retry: false,
225 },
226 },
227 })
228​
229 const host = new TestControllerHost()
230 let resolveRefetch: (() => void) | undefined
231​
232 const infinite = createInfiniteQueryController(
233 host,
234 {
235 queryKey: ['infinite-controller', 'tracked-data-only'],
236 initialPageParam: 0,
237 initialData: {
238 pages: ['stable-page'],
239 pageParams: [0],
240 },
241 staleTime: Infinity,
242 queryFn: () =>
243 new Promise<string>((resolve) => {
244 resolveRefetch = () => resolve('stable-page')
245 }),
246 getNextPageParam: () => undefined,
247 },
248 client,
249 )
250​
251 try {
252 host.connect()
253 host.update()
254​
255 expect(infinite().data?.pages).toEqual(['stable-page'])
256​
257 await Promise.resolve()
258 await Promise.resolve()
259​
260 host.updatesRequested = 0
261​
262 const refetch = infinite.refetch()
263​
264 await waitFor(() => resolveRefetch !== undefined)
265 await Promise.resolve()
266​
267 expect(host.updatesRequested).toBe(0)
268​
269 resolveRefetch!()
270 await refetch
271 await Promise.resolve()
272​
273 expect(host.updatesRequested).toBe(0)
274 } finally {
275 infinite.destroy()
276 }
277 })
278​
279 it('refreshes a suppressed result on the next accessor read when a newly read property changed', async () => {
280 const client = new QueryClient({
281 defaultOptions: {
282 queries: {
283 retry: false,
284 },
285 },
286 })
287​
288 const queryKey = ['infinite-controller', 'late-read-freshness'] as const
289 const host = new TestControllerHost()
290​
291 const infinite = createInfiniteQueryController(
292 host,
293 {
294 queryKey,
295 initialPageParam: 0,
296 initialData: {
297 pages: ['initial-page'],
298 pageParams: [0],
299 },
300 staleTime: Infinity,
301 queryFn: async () => 'unused',
302 getNextPageParam: () => undefined,
303 },
304 client,
305 )
306​
307 try {
308 host.connect()
309 host.update()
310​
311 expect(infinite().status).toBe('success')
312​
313 await Promise.resolve()
314 await Promise.resolve()
315​
316 host.updatesRequested = 0
317​
318 client.setQueryData(queryKey, {
319 pages: ['updated-page'],
320 pageParams: [0],
321 })
322 await Promise.resolve()
323​
324 expect(infinite().data?.pages).toEqual(['updated-page'])
325 expect(host.updatesRequested).toBe(0)
326 } finally {
327 infinite.destroy()
328 }
329 })
330​
331 it('INFEDGE-01: next-page failure preserves prior pages consistently', async () => {
332 const client = new QueryClient({
333 defaultOptions: {
334 queries: {
335 retry: false,
336 },
337 },
338 })
339​
340 const host = new TestControllerHost()
341 const infinite = createInfiniteQueryController(
342 host,
343 {
344 queryKey: ['infedge-01'],
345 initialPageParam: 0,
346 queryFn: async ({ pageParam }) => {
347 const page = Number(pageParam)
348 if (page === 1) {
349 throw new Error('next-page-failed')
350 }
351 return page
352 },
353 getNextPageParam: (lastPage) =>
354 lastPage < 1 ? lastPage + 1 : undefined,
355 },
356 client,
357 )
358​
359 host.connect()
360 host.update()
361​
362 await waitFor(() => infinite().isSuccess)
363 expect(infinite().data?.pages).toEqual([0])
364​
365 const nextPageResult = await infinite.fetchNextPage()
366 expect(nextPageResult.isFetchNextPageError).toBe(true)
367 expect(nextPageResult.error).toBeInstanceOf(Error)
368 await waitFor(() => infinite().isFetchNextPageError)
369 expect(infinite().data?.pages).toEqual([0])
370 })
371​
372 it('LC-INF-03: missing provider fails deterministically and imperative methods align', async () => {
373 const consumer = document.createElement(
374 contextInfiniteTagName,
375 ) as ContextInfiniteHostElement
376 const placeholderResult = consumer.infinite()
377​
378 expect(placeholderResult.status).toBe('pending')
379​
380 document.body.append(consumer)
381​
382 expect(() => consumer.infinite()).not.toThrow()
383 await waitForMissingQueryClient(() => consumer.infinite())
384​
385 await expect(consumer.infinite.refetch()).rejects.toThrow(
386 /No QueryClient available/,
387 )
388 await expect(consumer.infinite.fetchNextPage()).rejects.toThrow(
389 /No QueryClient available/,
390 )
391 await expect(placeholderResult.refetch()).rejects.toThrow(
392 /No QueryClient available/,
393 )
394 await expect(placeholderResult.fetchNextPage()).rejects.toThrow(
395 /No QueryClient available/,
396 )
397 await expect(placeholderResult.fetchPreviousPage()).rejects.toThrow(
398 /No QueryClient available/,
399 )
400​
401 consumer.infinite.destroy()
402 consumer.remove()
403 await Promise.resolve()
404 })
405​
406 it('ALREADYCONN-INF-01: infinite query controller on already-connected host with explicit client does not throw', async () => {
407 const client = new QueryClient({
408 defaultOptions: {
409 queries: {
410 retry: false,
411 },
412 },
413 })
414 client.setQueryData(['already-connected-infinite'], {
415 pages: [0],
416 pageParams: [0],
417 })
418​
419 class AlreadyConnectedHost implements ReactiveControllerHost {
420 private readonly controllers = new Set<ReactiveController>()
421 private isConnected = true
422 updatesRequested = 0
423 readonly updateComplete: Promise<boolean> = Promise.resolve(true)
424​
425 addController(controller: ReactiveController): void {
426 this.controllers.add(controller)
427 if (this.isConnected) {
428 controller.hostConnected?.()
429 }
430 }
431​
432 removeController(controller: ReactiveController): void {
433 this.controllers.delete(controller)
434 }
435​
436 requestUpdate(): void {
437 this.updatesRequested += 1
438 }
439 }
440​
441 const host = new AlreadyConnectedHost()
442 const infinite = createInfiniteQueryController(
443 host,
444 {
445 queryKey: ['already-connected-infinite'],
446 initialPageParam: 0,
447 queryFn: async ({ pageParam }) => Number(pageParam),
448 getNextPageParam: (lastPage) =>
449 lastPage < 1 ? lastPage + 1 : undefined,
450 staleTime: 30_000,
451 },
452 client,
453 )
454​
455 await Promise.resolve()
456 await Promise.resolve()
457​
458 expect(infinite().isSuccess).toBe(true)
459 expect(infinite().data?.pages).toEqual([0])
460​
461 infinite.destroy()
462 })
463​
464 it('LC-INF-04: explicit-client infinite accessors defer until host fields are initialized', () => {
465 const client = new QueryClient()
466​
467 class DeferredExplicitInfiniteHost implements ReactiveControllerHost {
468 private readonly controllers = new Set<ReactiveController>()
469​
470 updatesRequested = 0
471 readonly updateComplete: Promise<boolean> = Promise.resolve(true)
472​
473 readonly infinite = createInfiniteQueryController(
474 this,
475 () => ({
476 queryKey: ['deferred-explicit-infinite', this.id] as const,
477 initialPageParam: 0,
478 queryFn: async ({ pageParam }) => Number(pageParam),
479 getNextPageParam: (lastPage) =>
480 lastPage < 1 ? lastPage + 1 : undefined,
481 retry: false,
482 }),
483 client,
484 )
485​
486 readonly firstRead = this.infinite()
487 readonly id = 'alpha'
488​
489 addController(controller: ReactiveController): void {
490 this.controllers.add(controller)
491 }
492​
493 removeController(controller: ReactiveController): void {
494 this.controllers.delete(controller)
495 }
496​
497 requestUpdate(): void {
498 this.updatesRequested += 1
499 }
500 }
501​
502 expect(() => new DeferredExplicitInfiniteHost()).not.toThrow()
503​
504 const host = new DeferredExplicitInfiniteHost()
505 expect(host.infinite().status).toBe('pending')
506​
507 host.infinite.destroy()
508 })
509})
510​
511describe('options helpers integration', () => {
512 it('OPT-01: queryOptions integrates with createQueryController', async () => {
513 const client = new QueryClient({
514 defaultOptions: {
515 queries: {
516 retry: false,
517 },
518 },
519 })
520 const host = new TestControllerHost()
521​
522 const query = createQueryController(
523 host,
524 queryOptions({
525 queryKey: ['opt-01', 'query'] as const,
526 queryFn: async () => 'query-ok',
527 }),
528 client,
529 )
530​
531 host.connect()
532 host.update()
533 await waitFor(() => query().isSuccess)
534 expect(query().data).toBe('query-ok')
535 })
536​
537 it('OPT-01: mutationOptions integrates with createMutationController', async () => {
538 const client = new QueryClient()
539 const host = new TestControllerHost()
540​
541 const mutation = createMutationController(
542 host,
543 mutationOptions({
544 mutationFn: async (value: number) => value + 10,
545 }),
546 client,
547 )
548​
549 host.connect()
550 host.update()
551 await expect(mutation.mutateAsync(5)).resolves.toBe(15)
552 expect(mutation().isSuccess).toBe(true)
553 })
554​
555 it('OPT-01: infiniteQueryOptions integrates with createInfiniteQueryController', async () => {
556 const client = new QueryClient({
557 defaultOptions: {
558 queries: {
559 retry: false,
560 },
561 },
562 })
563 const host = new TestControllerHost()
564​
565 const infinite = createInfiniteQueryController(
566 host,
567 infiniteQueryOptions({
568 queryKey: ['opt-01', 'infinite'],
569 initialPageParam: 0,
570 queryFn: async ({ pageParam }) => Number(pageParam),
571 getNextPageParam: (lastPage) =>
572 lastPage < 1 ? lastPage + 1 : undefined,
573 }),
574 client,
575 )
576​
577 host.connect()
578 host.update()
579 await waitFor(() => infinite().isSuccess)
580 expect(infinite().data?.pages).toEqual([0])
581 })
582})