Open History to see the last commit
1import { act, renderHook, waitFor } from '@testing-library/react'
2import { describe, expect, it, vi } from 'vitest'
3import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
4import {
5 QueryClient,
6 createServerPaginationFixture,
7} from '../../query-db-collection/tests/server-pagination-fixture'
8import { Func, PropRef, Value } from '../../db/src/query/ir'
9import type { ServerRow } from '../../query-db-collection/tests/server-pagination-fixture'
10import type { LoadSubsetOptions } from '@tanstack/db'
11
12const rows = Array.from({ length: 8 }, (_, id) => ({ id, rank: id }))
13const pageCases = [1, 2, 3, 5].flatMap((serverPageSize) =>
14 [1, 2, 5].flatMap((pageSize) =>
15 [0, 1, 8].map((rowCount) => ({ serverPageSize, pageSize, rowCount })),
16 ),
17)
18
19type ServerFixture = ReturnType<typeof createServerPaginationFixture>
20type PageSnapshot = {
21 data: ReadonlyArray<ServerRow>
22 pages: ReadonlyArray<ReadonlyArray<ServerRow>>
23 pageParams: ReadonlyArray<number>
24}
25
26function expectPageContents(
27 snapshot: PageSnapshot,
28 sourceRows: ReadonlyArray<ServerRow>,
29 pageSize: number,
30 committedPages: number,
31 initialPageParam = 0,
32): void {
33 // Compare both fixture fields without sorting or using actual page lengths
34 // to construct the expected partition. Virtual metadata is not this law.
35 const contents = (page: ReadonlyArray<ServerRow>) =>
36 page.map(({ id, rank }) => ({ id, rank }))
37 expect(contents(snapshot.data)).toEqual(
38 sourceRows.slice(0, pageSize * committedPages),
39 )
40 expect(snapshot.pages.map(contents)).toEqual(
41 Array.from({ length: committedPages }, (_, index) =>
42 sourceRows.slice(index * pageSize, (index + 1) * pageSize),
43 ),
44 )
45 expect(snapshot.pageParams).toEqual(
46 Array.from(
47 { length: committedPages },
48 (_, index) => initialPageParam + index,
49 ),
50 )
51}
52
53type ProbeCollection = { cleanup: () => Promise<void> }
54type MountedProbe = {
55 unmount: () => void
56 result: { current: { collection?: ProbeCollection } }
57}
58
59async function withServerFixture(
60 options: Parameters<typeof createServerPaginationFixture>[0],
61 run: (
62 fixture: ServerFixture,
63 mount: <T extends MountedProbe>(create: () => T) => T,
64 ) => void | Promise<void>,
65): Promise<void> {
66 let fixture: ServerFixture | undefined
67 let mounted: MountedProbe | undefined
68 let failed = false
69 let primaryError: unknown
70 try {
71 fixture = createServerPaginationFixture(options)
72 await run(fixture, (create) => {
73 const hook = create()
74 mounted = hook
75 return hook
76 })
77 } catch (error) {
78 failed = true
79 primaryError = error
80 }
81 const cleanupErrors: Array<unknown> = []
82 let live: ProbeCollection | undefined
83 try {
84 // Capture the query handle before unmount changes its subscription state.
85 live = mounted?.result.current.collection
86 } catch (error) {
87 cleanupErrors.push(error)
88 }
89 for (const cleanup of [
90 () => mounted?.unmount(),
91 () => live?.cleanup(),
92 () => fixture?.collection.cleanup(),
93 () => fixture?.client.clear(),
94 ]) {
95 try {
96 await cleanup()
97 } catch (error) {
98 cleanupErrors.push(error)
99 }
100 }
101 if (cleanupErrors.length) {
102 if (failed) {
103 throw new AggregateError(
104 [primaryError, ...cleanupErrors],
105 `Server pagination probe and cleanup failed`,
106 { cause: primaryError },
107 )
108 }
109 if (cleanupErrors.length === 1) throw cleanupErrors[0]
110 throw new AggregateError(cleanupErrors, `Server pagination cleanup failed`)
111 }
112 if (failed) throw primaryError
113}
114
115describe(`server pagination contract probes`, () => {
116 const boundaryRows = [
117 { id: 4, rank: 1 },
118 { id: 7, rank: 1 },
119 { id: 2, rank: 3 },
120 { id: 9, rank: 4 },
121 ]
122 const rankOrder = () => [
123 {
124 expression: new PropRef([`rank`]),
125 compareOptions: { direction: `asc` as const, nulls: `last` as const },
126 },
127 ]
128 const comparison = (name: string, field: `id` | `rank`, value: number) =>
129 new Func<boolean>(name, [new PropRef([field]), new Value(value)])
130 const validRequests: Array<{
131 name: string
132 subset: LoadSubsetOptions | undefined
133 expected: Array<ServerRow>
134 }> = [
135 { name: `full source`, subset: undefined, expected: boundaryRows },
136 { name: `unwindowed`, subset: {}, expected: boundaryRows },
137 {
138 name: `unlimited tie`,
139 subset: { where: comparison(`eq`, `rank`, 1) },
140 expected: boundaryRows.slice(0, 2),
141 },
142 {
143 name: `leading rank order`,
144 subset: { orderBy: rankOrder(), limit: 3 },
145 expected: boundaryRows.slice(0, 3),
146 },
147 {
148 name: `full rank/id order`,
149 subset: {
150 orderBy: [
151 ...rankOrder(),
152 {
153 expression: new PropRef([`id`]),
154 compareOptions: {
155 direction: `asc`,
156 nulls: `first`,
157 stringSort: `lexical`,
158 },
159 },
160 ],
161 offset: 1,
162 limit: 2,
163 },
164 expected: boundaryRows.slice(1, 3),
165 },
166 {
167 name: `zero limit`,
168 subset: { orderBy: rankOrder(), limit: 0 },
169 expected: [],
170 },
171 {
172 name: `false predicate`,
173 subset: { where: new Value(false) },
174 expected: [],
175 },
176 {
177 name: `empty membership`,
178 subset: { where: new Func(`in`, [new PropRef([`id`]), new Value([])]) },
179 expected: [],
180 },
181 {
182 name: `all Boolean branches`,
183 subset: {
184 where: new Func(`and`, [
185 new Func(`or`, [
186 comparison(`eq`, `id`, 4),
187 new Func(`in`, [new PropRef([`id`]), new Value([7, 2])]),
188 ]),
189 new Func(`not`, [comparison(`eq`, `rank`, 3)]),
190 ]),
191 },
192 expected: boundaryRows.slice(0, 2),
193 },
194 {
195 name: `greater`,
196 subset: { where: comparison(`gt`, `rank`, 1) },
197 expected: boundaryRows.slice(2),
198 },
199 {
200 name: `greater equal`,
201 subset: { where: comparison(`gte`, `rank`, 3) },
202 expected: boundaryRows.slice(2),
203 },
204 {
205 name: `less`,
206 subset: { where: comparison(`lt`, `rank`, 3) },
207 expected: boundaryRows.slice(0, 2),
208 },
209 {
210 name: `less equal`,
211 subset: { where: comparison(`lte`, `rank`, 1) },
212 expected: boundaryRows.slice(0, 2),
213 },
214 {
215 name: `offset ignores separately validated cursor`,
216 subset: {
217 orderBy: rankOrder(),
218 offset: 1,
219 limit: 2,
220 cursor: {
221 whereFrom: comparison(`gt`, `rank`, 3),
222 whereCurrent: comparison(`eq`, `rank`, 3),
223 lastKey: 2,
224 },
225 },
226 expected: boundaryRows.slice(1, 3),
227 },
228 ]
229 it.each(validRequests)(
230 `serves the finite numeric boundary: $name`,
231 async ({ subset, expected }) => {
232 await withServerFixture(
233 {
234 rows: boundaryRows,
235 syncMode: `on-demand`,
236 order: [`rank`, `id`],
237 serverPageSize: 2,
238 },
239 async (fixture) => {
240 expect(await fixture.fetchRows(subset)).toEqual(expected)
241 expect(fixture.requests).toHaveLength(1)
242 },
243 )
244 },
245 )
246
247 const unsupported = new Func(`unsupported`, [])
248 const malformedRequests: Array<{ name: string; subset: unknown }> = [
249 { name: `missing finite order`, subset: { limit: 2 } },
250 {
251 name: `wrong first field`,
252 subset: {
253 orderBy: [{ ...rankOrder()[0], expression: new PropRef([`id`]) }],
254 limit: 2,
255 },
256 },
257 {
258 name: `reversed direction`,
259 subset: {
260 orderBy: [
261 {
262 expression: new PropRef([`rank`]),
263 compareOptions: { direction: `desc`, nulls: `last` },
264 },
265 ],
266 },
267 },
268 {
269 name: `constant order`,
270 subset: { orderBy: [{ ...rankOrder()[0], expression: new Value(1) }] },
271 },
272 { name: `empty order`, subset: { orderBy: [] } },
273 { name: `negative offset`, subset: { offset: -1 } },
274 { name: `fractional offset`, subset: { offset: 0.5 } },
275 { name: `infinite limit`, subset: { limit: Infinity } },
276 { name: `NaN limit`, subset: { limit: NaN } },
277 { name: `unknown option`, subset: { extra: true } },
278 {
279 name: `unknown comparison option`,
280 subset: {
281 orderBy: [
282 {
283 expression: new PropRef([`rank`]),
284 compareOptions: { direction: `asc`, nulls: `last`, custom: true },
285 },
286 ],
287 },
288 },
289 {
290 name: `unsupported locale payload`,
291 subset: {
292 orderBy: [
293 {
294 expression: new PropRef([`rank`]),
295 compareOptions: {
296 direction: `asc`,
297 nulls: `last`,
298 stringSort: `locale`,
299 locale: `en`,
300 },
301 },
302 ],
303 },
304 },
305 {
306 name: `hidden false branch`,
307 subset: { where: new Func(`and`, [new Value(false), unsupported]) },
308 },
309 {
310 name: `hidden true branch`,
311 subset: { where: new Func(`or`, [new Value(true), unsupported]) },
312 },
313 {
314 name: `wrong arity`,
315 subset: { where: new Func(`eq`, [new PropRef([`rank`])]) },
316 },
317 {
318 name: `nonfinite membership`,
319 subset: {
320 where: new Func(`in`, [
321 new PropRef([`rank`]),
322 new Value([1, Infinity]),
323 ]),
324 },
325 },
326 {
327 name: `wrong reference path`,
328 subset: {
329 where: new Func(`eq`, [new PropRef([`row`, `rank`]), new Value(1)]),
330 },
331 },
332 { name: `numeric predicate`, subset: { where: new Value(1) } },
333 {
334 name: `hidden cursor branch`,
335 subset: {
336 cursor: {
337 whereFrom: new Func(`or`, [new Value(true), unsupported]),
338 whereCurrent: comparison(`eq`, `rank`, 1),
339 },
340 },
341 },
342 ]
343 for (const empty of [false, true]) {
344 it.each(malformedRequests)(
345 `rejects the whole request before filtering, empty=${empty}: $name`,
346 async ({ subset }) => {
347 await withServerFixture(
348 {
349 rows: empty ? [] : boundaryRows,
350 syncMode: `on-demand`,
351 order: [`rank`, `id`],
352 },
353 async (fixture) => {
354 await expect(
355 fixture.fetchRows(subset as LoadSubsetOptions),
356 ).rejects.toThrow(`Unsupported server pagination request`)
357 expect(fixture.requests).toEqual([])
358 expect(fixture.serverPages).toEqual([])
359 },
360 )
361 },
362 )
363 }
364
365 it(`detaches static requests before awaiting endpoint pages but keeps resource handles live`, async () => {
366 await withServerFixture(
367 {
368 rows: boundaryRows,
369 syncMode: `on-demand`,
370 order: [`rank`, `id`],
371 serverPageSize: 1,
372 },
373 async (fixture) => {
374 const members = [4, 7, 2, 9]
375 const ref = new PropRef([`rank`])
376 const order = {
377 expression: ref,
378 compareOptions: {
379 direction: `asc` as `asc` | `desc`,
380 nulls: `last` as const,
381 stringSort: `locale` as const,
382 },
383 }
384 const from = new Value(3)
385 const abort = new AbortController()
386 // The guarded source owns this subscription even if a later check throws.
387 const subscription = fixture.collection.subscribeChanges(() => {})
388 const entryStatus = subscription.status
389 const subset: LoadSubsetOptions = {
390 where: new Func(`in`, [new PropRef([`id`]), new Value(members)]),
391 orderBy: [order],
392 offset: 1,
393 limit: 2,
394 cursor: {
395 whereFrom: new Func(`gt`, [new PropRef([`rank`]), from]),
396 whereCurrent: comparison(`eq`, `rank`, 3),
397 lastKey: 2,
398 },
399 signal: abort.signal,
400 subscription,
401 }
402 const pending = fixture.fetchRows(subset)
403 void pending.catch(() => undefined)
404 members[0] = 99
405 ref.path[0] = `id`
406 order.compareOptions.direction = `desc`
407 from.value = 99
408 subset.offset = 0
409 subset.limit = 0
410 abort.abort()
411 subscription.unsubscribe()
412 expect(await pending).toEqual(boundaryRows.slice(1, 3))
413 const captured = fixture.requests.find(
414 (request) => request.subset?.signal === abort.signal,
415 )!
416 expect(captured.subset?.where).toEqual(
417 new Func(`in`, [new PropRef([`id`]), new Value([4, 7, 2, 9])]),
418 )
419 expect(captured.subset?.orderBy).toEqual([
420 {
421 expression: new PropRef([`rank`]),
422 compareOptions: {
423 direction: `asc`,
424 nulls: `last`,
425 stringSort: `locale`,
426 },
427 },
428 ])
429 expect(captured.subset?.cursor).toEqual({
430 whereFrom: comparison(`gt`, `rank`, 3),
431 whereCurrent: comparison(`eq`, `rank`, 3),
432 lastKey: 2,
433 })
434 expect(captured.subset?.offset).toBe(1)
435 expect(captured.subset?.limit).toBe(2)
436 expect(captured.subset?.signal).toBe(abort.signal)
437 expect(captured.signalAborted).toBe(false)
438 expect(captured.subset?.signal?.aborted).toBe(true)
439 expect(Object.isFrozen(abort.signal)).toBe(false)
440 expect(captured.subset?.subscription).toBe(subscription)
441 expect(captured.subscriptionStatus).toBe(entryStatus)
442 expect(captured.subset?.subscription?.status).toBe(subscription.status)
443 expect(Object.isFrozen(subscription)).toBe(false)
444 },
445 )
446 })
447
448 for (const cleanupFails of [false, true]) {
449 it(`clears the client on fixture construction failure, cleanup fails=${cleanupFails}`, () => {
450 const primary = undefined
451 const secondary = new Error(`client clear failed after disposal`)
452 const clear = QueryClient.prototype.clear
453 let cleared = 0
454 const spy = vi
455 .spyOn(QueryClient.prototype, `clear`)
456 .mockImplementation(function (this: QueryClient) {
457 clear.call(this)
458 cleared++
459 if (cleanupFails) throw secondary
460 })
461 let failed = false
462 let caught: unknown
463 try {
464 try {
465 createServerPaginationFixture({
466 rows,
467 get syncMode(): `eager` {
468 throw primary
469 },
470 })
471 } catch (error) {
472 failed = true
473 caught = error
474 }
475 expect(failed).toBe(true)
476 expect(cleared).toBe(1)
477 if (cleanupFails) {
478 expect(caught).toBeInstanceOf(AggregateError)
479 expect(Object.hasOwn(caught as AggregateError, `cause`)).toBe(true)
480 expect((caught as AggregateError).cause).toBe(primary)
481 expect((caught as AggregateError).errors).toEqual([
482 primary,
483 secondary,
484 ])
485 expect((caught as AggregateError).errors[1]).toBe(secondary)
486 } else expect(caught).toBe(primary)
487 } finally {
488 spy.mockRestore()
489 }
490 })
491 }
492
493 it(`cleans the source and client when React mount throws before returning a handle`, async () => {
494 const failure = new Error(`React mount failed`)
495 let owned: ServerFixture | undefined
496 let cleared = 0
497 const error = vi.spyOn(console, `error`).mockImplementation(() => {})
498 try {
499 await expect(
500 withServerFixture(
501 { rows, syncMode: `on-demand`, order: [`id`] },
502 (fixture, mount) => {
503 owned = fixture
504 const clear = fixture.client.clear.bind(fixture.client)
505 fixture.client.clear = () => {
506 cleared++
507 clear()
508 }
509 mount(() =>
510 renderHook(() => {
511 throw failure
512 }),
513 )
514 },
515 ),
516 ).rejects.toBe(failure)
517 expect(owned?.collection.status).toBe(`cleaned-up`)
518 expect(owned?.collection.subscriberCount).toBe(0)
519 expect(owned?.client.getQueryCache().getAll()).toEqual([])
520 expect(cleared).toBe(1)
521 } finally {
522 error.mockRestore()
523 }
524 })
525
526 for (const cleanupFails of [false, true]) {
527 it(`retains a body failure and attempts every resource cleanup, cleanup fails=${cleanupFails}`, async () => {
528 const failure = new Error(`Pagination body failed`)
529 const cleanupFailures = [
530 new Error(`Unmount failed after disposal`),
531 new Error(`Query cleanup failed after disposal`),
532 new Error(`Source cleanup failed after disposal`),
533 new Error(`Client clear failed after disposal`),
534 ]
535 const cleaned: Array<string> = []
536 let owned: ServerFixture | undefined
537 let live: (ProbeCollection & { readonly status: string }) | undefined
538 let caught: unknown
539 try {
540 await withServerFixture(
541 { rows, syncMode: `on-demand`, order: [`id`] },
542 async (fixture, mount) => {
543 owned = fixture
544 const hook = mount(() =>
545 renderHook(() =>
546 useLiveInfiniteQuery(
547 (q) =>
548 q
549 .from({ row: fixture.collection })
550 .orderBy(({ row }) => row.id),
551 { pageSize: 2 },
552 ),
553 ),
554 )
555 await waitFor(() => expect(hook.result.current.isReady).toBe(true))
556 live = hook.result.current.collection
557 if (!live) throw new Error(`Missing mounted query Collection`)
558 const unmount = hook.unmount
559 hook.unmount = () => {
560 unmount()
561 cleaned.push(`hook`)
562 if (cleanupFails) throw cleanupFailures[0]
563 }
564 const cleanLive = live.cleanup.bind(live)
565 live.cleanup = async () => {
566 await cleanLive()
567 cleaned.push(`query`)
568 if (cleanupFails) throw cleanupFailures[1]
569 }
570 const cleanSource = fixture.collection.cleanup.bind(
571 fixture.collection,
572 )
573 fixture.collection.cleanup = async () => {
574 await cleanSource()
575 cleaned.push(`source`)
576 if (cleanupFails) throw cleanupFailures[2]
577 }
578 const clear = fixture.client.clear.bind(fixture.client)
579 fixture.client.clear = () => {
580 clear()
581 cleaned.push(`client`)
582 if (cleanupFails) throw cleanupFailures[3]
583 }
584 throw failure
585 },
586 )
587 } catch (error) {
588 caught = error
589 }
590 if (cleanupFails) {
591 expect(caught).toBeInstanceOf(AggregateError)
592 const compound = caught as AggregateError
593 expect(compound.cause).toBe(failure)
594 expect(compound.errors).toHaveLength(5)
595 for (const [index, expected] of [
596 failure,
597 ...cleanupFailures,
598 ].entries()) {
599 expect(compound.errors[index]).toBe(expected)
600 }
601 } else {
602 expect(caught).toBe(failure)
603 }
604 expect(cleaned).toEqual([`hook`, `query`, `source`, `client`])
605 expect(live?.status).toBe(`cleaned-up`)
606 expect(owned?.collection.status).toBe(`cleaned-up`)
607 expect(owned?.collection.subscriberCount).toBe(0)
608 expect(owned?.client.getQueryCache().getAll()).toEqual([])
609 })
610 }
611
612 it(`rejects a server-page callback before constructing a query`, () => {
613 const queryFn = vi.fn(() => {
614 throw new Error(`query must not be constructed`)
615 })
616 const config = { pageSize: 2, getNextPageParam: () => 1 }
617 const error = vi.spyOn(console, `error`).mockImplementation(() => {})
618 try {
619 expect(() =>
620 renderHook(() => useLiveInfiniteQuery(queryFn, config)),
621 ).toThrow(`getNextPageParam is not supported`)
622 expect(queryFn).not.toHaveBeenCalled()
623 } finally {
624 error.mockRestore()
625 }
626 })
627
628 it.each(pageCases)(
629 `drains server pages of $serverPageSize for UI pages of $pageSize over $rowCount rows`,
630 async ({ serverPageSize, pageSize, rowCount }) => {
631 const sourceRows = rows.slice(0, rowCount)
632 await withServerFixture(
633 {
634 rows: sourceRows,
635 syncMode: `on-demand`,
636 order: [`id`],
637 serverPageSize,
638 },
639 async (fixture, mount) => {
640 const { result } = mount(() =>
641 renderHook(() =>
642 useLiveInfiniteQuery(
643 (q) =>
644 q
645 .from({ row: fixture.collection })
646 .orderBy(({ row }) => row.id),
647 { pageSize },
648 ),
649 ),
650 )
651 await waitFor(() => expect(result.current.isReady).toBe(true))
652 for (let size = pageSize; ; size += pageSize) {
653 expectPageContents(
654 result.current,
655 sourceRows,
656 pageSize,
657 size / pageSize,
658 )
659 expect(result.current.data.map((row) => row.id)).toEqual(
660 sourceRows.slice(0, size).map((row) => row.id),
661 )
662 expect(result.current.hasNextPage).toBe(size < rowCount)
663 if (size >= rowCount) break
664 await act(() => result.current.fetchNextPage())
665 }
666 if (rowCount > serverPageSize)
667 expect(fixture.serverPages.length).toBeGreaterThan(1)
668 if (rowCount > pageSize + 1) {
669 expect(
670 fixture.requests.some(
671 (request) => (request.subset?.offset ?? 0) > 0,
672 ),
673 ).toBe(true)
674 }
675 },
676 )
677 },
678 )
679
680 it(`retains a tie group across backend and UI page boundaries`, async () => {
681 // Already sorted by rank, then id. IDs decrease between groups so an
682 // accidental id-first order cannot produce the expected result.
683 const sourceRows = [
684 ...Array.from({ length: 6 }, (_, index) => ({ id: index + 10, rank: 1 })),
685 ...Array.from({ length: 3 }, (_, index) => ({ id: index + 1, rank: 2 })),
686 ]
687 await withServerFixture(
688 {
689 rows: sourceRows,
690 syncMode: `on-demand`,
691 order: [`rank`, `id`],
692 serverPageSize: 2,
693 },
694 async (fixture, mount) => {
695 const { result } = mount(() =>
696 renderHook(() =>
697 useLiveInfiniteQuery(
698 (q) =>
699 q
700 .from({ row: fixture.collection })
701 .orderBy(({ row }) => row.rank)
702 .orderBy(({ row }) => row.id),
703 { pageSize: 3 },
704 ),
705 ),
706 )
707 await waitFor(() => expect(result.current.isReady).toBe(true))
708 for (const size of [3, 6, 9]) {
709 expectPageContents(result.current, sourceRows, 3, size / 3)
710 expect(result.current.data.map((row) => row.id)).toEqual(
711 sourceRows.slice(0, size).map((row) => row.id),
712 )
713 expect(result.current.hasNextPage).toBe(size < sourceRows.length)
714 if (size < sourceRows.length)
715 await act(() => result.current.fetchNextPage())
716 }
717 expect(new Set(fixture.serverPages)).toEqual(new Set([0, 1, 2, 3, 4]))
718 const requestCount = fixture.requests.length
719 await act(() => result.current.fetchNextPage())
720 expect(fixture.requests).toHaveLength(requestCount)
721 expectPageContents(result.current, sourceRows, 3, 3)
722 },
723 )
724 })
725
726 it(`eager page responses remain local data, not an infinite-query transport`, async () => {
727 await withServerFixture(
728 {
729 rows,
730 syncMode: `eager`,
731 cap: 4,
732 },
733 async (fixture, mount) => {
734 const { result } = mount(() =>
735 renderHook(() =>
736 useLiveInfiniteQuery(
737 (q) =>
738 q
739 .from({ row: fixture.collection })
740 .orderBy(({ row }) => row.id),
741 { pageSize: 2, initialPageParam: 10 },
742 ),
743 ),
744 )
745 await waitFor(() => expect(result.current.isReady).toBe(true))
746 expect(result.current.data.map((row) => row.id)).toEqual([0, 1])
747 expect(result.current.pageParams).toEqual([10])
748 expectPageContents(result.current, rows.slice(0, 4), 2, 1, 10)
749 await act(() => result.current.fetchNextPage())
750 expect(result.current.data.map((row) => row.id)).toEqual([0, 1, 2, 3])
751 expect(result.current.pageParams).toEqual([10, 11])
752 expectPageContents(result.current, rows.slice(0, 4), 2, 2, 10)
753 expect(result.current.hasNextPage).toBe(false)
754 await act(() => result.current.fetchNextPage())
755 expect(fixture.requests).toHaveLength(1)
756 expect(fixture.requests[0]?.pageParam).toBeUndefined()
757 expectPageContents(result.current, rows.slice(0, 4), 2, 2, 10)
758 },
759 )
760 })
761
762 it(`on-demand pages continue by leading cursor and retain earlier rows`, async () => {
763 await withServerFixture(
764 {
765 rows,
766 syncMode: `on-demand`,
767 order: [`id`, `rank`],
768 },
769 async (fixture, mount) => {
770 const { result } = mount(() =>
771 renderHook(() =>
772 useLiveInfiniteQuery(
773 (q) =>
774 q
775 .from({ row: fixture.collection })
776 .orderBy(({ row }) => row.id)
777 .orderBy(({ row }) => row.rank),
778 { pageSize: 2 },
779 ),
780 ),
781 )
782 await waitFor(() => expect(result.current.isReady).toBe(true))
783 for (const size of [2, 4, 6, 8]) {
784 expectPageContents(result.current, rows, 2, size / 2)
785 expect(result.current.data.map((row) => row.id)).toEqual(
786 rows.slice(0, size).map((row) => row.id),
787 )
788 expect(result.current.hasNextPage).toBe(size < rows.length)
789 if (size < rows.length)
790 await act(() => result.current.fetchNextPage())
791 }
792 const limitedRequests = fixture.requests.filter(
793 (request) => request.subset?.limit !== undefined,
794 )
795 expect(limitedRequests.map((request) => request.subset!.limit)).toEqual(
796 [3, 2, 2, 2, 1],
797 )
798 expect(limitedRequests[0]?.subset?.cursor).toBeUndefined()
799 expect(
800 limitedRequests
801 .slice(1)
802 .every((request) => request.subset?.cursor !== undefined),
803 ).toBe(true)
804 expect(
805 fixture.requests.every((request) => request.pageParam === undefined),
806 ).toBe(true)
807 },
808 )
809 })
810
811 // Deliberately nonconforming provider: this is a protocol boundary control,
812 // not an oracle accepting truncated responses as successful pagination.
813 it(`a capped response can underfill locally while the server still has rows`, async () => {
814 await withServerFixture(
815 {
816 rows,
817 syncMode: `on-demand`,
818 order: [`id`, `rank`],
819 autoIndex: `off`,
820 cap: 2,
821 },
822 async (fixture, mount) => {
823 const { result } = mount(() =>
824 renderHook(() =>
825 useLiveInfiniteQuery(
826 (q) =>
827 q
828 .from({ row: fixture.collection })
829 .orderBy(({ row }) => row.id)
830 .orderBy(({ row }) => row.rank),
831 { pageSize: 2 },
832 ),
833 ),
834 )
835 await waitFor(() => expect(result.current.isReady).toBe(true))
836 expect(result.current.data.map((row) => row.id)).toEqual([0, 1])
837 expect(rows.length).toBeGreaterThan(result.current.data.length)
838 expectPageContents(result.current, rows.slice(0, 2), 2, 1)
839 expect(result.current.hasNextPage).toBe(false)
840 const requestCount = fixture.requests.length
841 await act(() => result.current.fetchNextPage())
842 expect(fixture.requests).toHaveLength(requestCount)
843 expectPageContents(result.current, rows.slice(0, 2), 2, 1)
844 },
845 )
846 })
847})