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

useLiveSuspenseQuery.test.tsx

685 lines17.3 KB

1import { describe, expect, it } from 'vitest'
2import { renderHook, waitFor } from '@testing-library/react'
3import {
4 createCollection,
5 createLiveQueryCollection,
6 eq,
7 gt,
8} from '@tanstack/db'
9import { StrictMode, Suspense } from 'react'
10import { useLiveSuspenseQuery } from '../src/useLiveSuspenseQuery'
11import { mockSyncCollectionOptions } from '../../db/tests/utils'
12import type { ReactNode } from 'react'
13​
14type Person = {
15 id: string
16 name: string
17 age: number
18 email: string
19 isActive: boolean
20 team: string
22​
23const initialPersons: Array<Person> = [
24 {
25 id: `1`,
26 name: `John Doe`,
27 age: 30,
28 email: `john.doe@example.com`,
29 isActive: true,
30 team: `team1`,
31 },
32 {
33 id: `2`,
34 name: `Jane Doe`,
35 age: 25,
36 email: `jane.doe@example.com`,
37 isActive: true,
38 team: `team2`,
39 },
40 {
41 id: `3`,
42 name: `John Smith`,
43 age: 35,
44 email: `john.smith@example.com`,
45 isActive: true,
46 team: `team1`,
47 },
49​
50// Wrapper component with Suspense
51function SuspenseWrapper({ children }: { children: ReactNode }) {
52 return <Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
54​
55describe(`useLiveSuspenseQuery`, () => {
56 it(`should suspend while loading and return data when ready`, async () => {
57 const collection = createCollection(
58 mockSyncCollectionOptions<Person>({
59 id: `test-persons-suspense-1`,
60 getKey: (person: Person) => person.id,
61 initialData: initialPersons,
62 }),
63 )
64​
65 const { result } = renderHook(
66 () => {
67 return useLiveSuspenseQuery((q) =>
68 q
69 .from({ persons: collection })
70 .where(({ persons }) => gt(persons.age, 30))
71 .select(({ persons }) => ({
72 id: persons.id,
73 name: persons.name,
74 age: persons.age,
75 })),
76 )
77 },
78 {
79 wrapper: SuspenseWrapper,
80 },
81 )
82​
83 // Wait for data to load
84 await waitFor(() => {
85 expect(result.current.state.size).toBe(1)
86 })
87​
88 expect(result.current.data).toHaveLength(1)
89 const johnSmith = result.current.data[0]
90 expect(johnSmith).toMatchObject({
91 id: `3`,
92 name: `John Smith`,
93 age: 35,
94 })
95 })
96​
97 it(`should return data that is always defined (type-safe)`, async () => {
98 const collection = createCollection(
99 mockSyncCollectionOptions<Person>({
100 id: `test-persons-suspense-2`,
101 getKey: (person: Person) => person.id,
102 initialData: initialPersons,
103 }),
104 )
105​
106 const { result } = renderHook(
107 () => {
108 return useLiveSuspenseQuery((q) => q.from({ persons: collection }))
109 },
110 {
111 wrapper: SuspenseWrapper,
112 },
113 )
114​
115 await waitFor(() => {
116 expect(result.current.data).toBeDefined()
117 })
118​
119 // Data is always defined - no optional chaining needed
120 expect(result.current.data.length).toBe(3)
121 // TypeScript will guarantee data is Array<Person>, not Array<Person> | undefined
122 })
123​
124 it(`should work with single result queries`, async () => {
125 const collection = createCollection(
126 mockSyncCollectionOptions<Person>({
127 id: `test-persons-suspense-3`,
128 getKey: (person: Person) => person.id,
129 initialData: initialPersons,
130 }),
131 )
132​
133 const { result } = renderHook(
134 () => {
135 return useLiveSuspenseQuery((q) =>
136 q
137 .from({ collection })
138 .where(({ collection: c }) => eq(c.id, `3`))
139 .findOne(),
140 )
141 },
142 {
143 wrapper: SuspenseWrapper,
144 },
145 )
146​
147 await waitFor(() => {
148 expect(result.current.state.size).toBe(1)
149 })
150​
151 expect(result.current.data).toMatchObject({
152 id: `3`,
153 name: `John Smith`,
154 age: 35,
155 })
156 })
157​
158 it(`should work with pre-created live query collection`, async () => {
159 const collection = createCollection(
160 mockSyncCollectionOptions<Person>({
161 id: `test-persons-suspense-4`,
162 getKey: (person: Person) => person.id,
163 initialData: initialPersons,
164 }),
165 )
166​
167 const liveQuery = createLiveQueryCollection((q) =>
168 q
169 .from({ persons: collection })
170 .where(({ persons }) => gt(persons.age, 30)),
171 )
172​
173 const { result } = renderHook(() => useLiveSuspenseQuery(liveQuery), {
174 wrapper: SuspenseWrapper,
175 })
176​
177 await waitFor(() => {
178 expect(result.current.data).toHaveLength(1)
179 })
180​
181 expect(result.current.data[0]).toMatchObject({
182 id: `3`,
183 name: `John Smith`,
184 age: 35,
185 })
186 })
187​
188 it(`should re-suspend when deps change`, async () => {
189 const collection = createCollection(
190 mockSyncCollectionOptions<Person>({
191 id: `test-persons-suspense-5`,
192 getKey: (person: Person) => person.id,
193 initialData: initialPersons,
194 }),
195 )
196​
197 const { result, rerender } = renderHook(
198 ({ minAge }) => {
199 return useLiveSuspenseQuery(
200 (q) =>
201 q
202 .from({ persons: collection })
203 .where(({ persons }) => gt(persons.age, minAge)),
204 [minAge],
205 )
206 },
207 {
208 wrapper: SuspenseWrapper,
209 initialProps: { minAge: 30 },
210 },
211 )
212​
213 // Initial load - age > 30
214 await waitFor(() => {
215 expect(result.current.data).toHaveLength(1)
216 })
217 expect(result.current.data[0]?.age).toBe(35)
218​
219 // Change deps - age > 20
220 rerender({ minAge: 20 })
221​
222 // Should re-suspend and load new data
223 await waitFor(() => {
224 expect(result.current.data).toHaveLength(3)
225 })
226 })
227​
228 it(`should reactively update data after initial load`, async () => {
229 const collection = createCollection(
230 mockSyncCollectionOptions<Person>({
231 id: `test-persons-suspense-6`,
232 getKey: (person: Person) => person.id,
233 initialData: initialPersons,
234 }),
235 )
236​
237 const { result } = renderHook(
238 () => useLiveSuspenseQuery((q) => q.from({ persons: collection })),
239 {
240 wrapper: SuspenseWrapper,
241 },
242 )
243​
244 // Wait for initial data
245 await waitFor(() => {
246 expect(result.current.data).toHaveLength(3)
247 })
248​
249 // Insert new person
250 collection.insert({
251 id: `4`,
252 name: `New Person`,
253 age: 40,
254 email: `new@example.com`,
255 isActive: true,
256 team: `team1`,
257 })
258​
259 // Should reactively update
260 await waitFor(() => {
261 expect(result.current.data).toHaveLength(4)
262 })
263 })
264​
265 it(`should throw error when query function returns undefined`, () => {
266 expect(() => {
267 renderHook(
268 () => {
269 return useLiveSuspenseQuery(() => undefined as any)
270 },
271 {
272 wrapper: SuspenseWrapper,
273 },
274 )
275 }).toThrow(/does not support disabled queries/)
276 })
277​
278 it(`should work with config object`, async () => {
279 const collection = createCollection(
280 mockSyncCollectionOptions<Person>({
281 id: `test-persons-suspense-7`,
282 getKey: (person: Person) => person.id,
283 initialData: initialPersons,
284 }),
285 )
286​
287 const { result } = renderHook(
288 () => {
289 return useLiveSuspenseQuery({
290 query: (q) => q.from({ persons: collection }),
291 })
292 },
293 {
294 wrapper: SuspenseWrapper,
295 },
296 )
297​
298 await waitFor(() => {
299 expect(result.current.data).toHaveLength(3)
300 })
301 })
302​
303 it(`should keep stable data references when data hasn't changed`, async () => {
304 const collection = createCollection(
305 mockSyncCollectionOptions<Person>({
306 id: `test-persons-suspense-8`,
307 getKey: (person: Person) => person.id,
308 initialData: initialPersons,
309 }),
310 )
311​
312 const { result, rerender } = renderHook(
313 () => useLiveSuspenseQuery((q) => q.from({ persons: collection })),
314 {
315 wrapper: SuspenseWrapper,
316 },
317 )
318​
319 await waitFor(() => {
320 expect(result.current.data).toHaveLength(3)
321 })
322​
323 const data1 = result.current.data
324​
325 rerender()
326​
327 const data2 = result.current.data
328​
329 // Data objects should be stable
330 expect(data1[0]).toBe(data2[0])
331 expect(data1[1]).toBe(data2[1])
332 expect(data1[2]).toBe(data2[2])
333 })
334​
335 it(`should handle multiple queries in same component (serial execution)`, async () => {
336 const personsCollection = createCollection(
337 mockSyncCollectionOptions<Person>({
338 id: `test-persons-suspense-9`,
339 getKey: (person: Person) => person.id,
340 initialData: initialPersons,
341 }),
342 )
343​
344 const { result } = renderHook(
345 () => {
346 const persons = useLiveSuspenseQuery((q) =>
347 q.from({ persons: personsCollection }),
348 )
349 const johnDoe = useLiveSuspenseQuery((q) =>
350 q
351 .from({ persons: personsCollection })
352 .where(({ persons: p }) => eq(p.id, `1`))
353 .findOne(),
354 )
355 return { persons, johnDoe }
356 },
357 {
358 wrapper: SuspenseWrapper,
359 },
360 )
361​
362 await waitFor(() => {
363 expect(result.current.persons.data).toHaveLength(3)
364 expect(result.current.johnDoe.data).toBeDefined()
365 })
366​
367 expect(result.current.johnDoe.data).toMatchObject({
368 id: `1`,
369 name: `John Doe`,
370 })
371 })
372​
373 it(`should cleanup collection when unmounted`, async () => {
374 const collection = createCollection(
375 mockSyncCollectionOptions<Person>({
376 id: `test-persons-suspense-10`,
377 getKey: (person: Person) => person.id,
378 initialData: initialPersons,
379 }),
380 )
381​
382 const { result, unmount } = renderHook(
383 () => useLiveSuspenseQuery((q) => q.from({ persons: collection })),
384 {
385 wrapper: SuspenseWrapper,
386 },
387 )
388​
389 await waitFor(() => {
390 expect(result.current.data).toHaveLength(3)
391 })
392​
393 const liveQueryCollection = result.current.collection
394 expect(liveQueryCollection.subscriberCount).toBeGreaterThan(0)
395​
396 unmount()
397​
398 // Collection should eventually be cleaned up (gcTime is 1ms)
399 await waitFor(
400 () => {
401 expect(liveQueryCollection.status).toBe(`cleaned-up`)
402 },
403 { timeout: 1000 },
404 )
405 })
406​
407 it(`should NOT re-suspend on live updates after initial load`, async () => {
408 const collection = createCollection(
409 mockSyncCollectionOptions<Person>({
410 id: `test-persons-suspense-11`,
411 getKey: (person: Person) => person.id,
412 initialData: initialPersons,
413 }),
414 )
415​
416 let suspenseCount = 0
417 const SuspenseCounter = ({ children }: { children: ReactNode }) => {
418 return (
419 <Suspense
420 fallback={
421 <div>
422 {(() => {
423 suspenseCount++
424 return `Loading...`
425 })()}
426 </div>
427 }
428 >
429 {children}
430 </Suspense>
431 )
432 }
433​
434 const { result } = renderHook(
435 () => useLiveSuspenseQuery((q) => q.from({ persons: collection })),
436 {
437 wrapper: SuspenseCounter,
438 },
439 )
440​
441 // Wait for initial load
442 await waitFor(() => {
443 expect(result.current.data).toHaveLength(3)
444 })
445​
446 const initialSuspenseCount = suspenseCount
447​
448 // Make multiple live updates
449 collection.insert({
450 id: `4`,
451 name: `New Person 1`,
452 age: 40,
453 email: `new1@example.com`,
454 isActive: true,
455 team: `team1`,
456 })
457​
458 await waitFor(() => {
459 expect(result.current.data).toHaveLength(4)
460 })
461​
462 collection.insert({
463 id: `5`,
464 name: `New Person 2`,
465 age: 45,
466 email: `new2@example.com`,
467 isActive: true,
468 team: `team2`,
469 })
470​
471 await waitFor(() => {
472 expect(result.current.data).toHaveLength(5)
473 })
474​
475 collection.delete(`4`)
476​
477 await waitFor(() => {
478 expect(result.current.data).toHaveLength(4)
479 })
480​
481 // Verify suspense count hasn't increased (no re-suspension)
482 expect(suspenseCount).toBe(initialSuspenseCount)
483 })
484​
485 it(`should only suspend on deps change, not on every re-render`, async () => {
486 const collection = createCollection(
487 mockSyncCollectionOptions<Person>({
488 id: `test-persons-suspense-12`,
489 getKey: (person: Person) => person.id,
490 initialData: initialPersons,
491 }),
492 )
493​
494 const { result, rerender } = renderHook(
495 ({ minAge }) =>
496 useLiveSuspenseQuery(
497 (q) =>
498 q
499 .from({ persons: collection })
500 .where(({ persons }) => gt(persons.age, minAge)),
501 [minAge],
502 ),
503 {
504 wrapper: SuspenseWrapper,
505 initialProps: { minAge: 20 },
506 },
507 )
508​
509 // Wait for initial load
510 await waitFor(() => {
511 expect(result.current.data).toHaveLength(3)
512 })
513​
514 const dataAfterInitial = result.current.data
515​
516 // Re-render with SAME deps - should NOT suspend (data stays available)
517 rerender({ minAge: 20 })
518 expect(result.current.data).toHaveLength(3)
519 expect(result.current.data).toBe(dataAfterInitial)
520​
521 rerender({ minAge: 20 })
522 expect(result.current.data).toHaveLength(3)
523​
524 rerender({ minAge: 20 })
525 expect(result.current.data).toHaveLength(3)
526​
527 // Change deps - SHOULD suspend and get new data
528 rerender({ minAge: 30 })
529​
530 await waitFor(() => {
531 expect(result.current.data).toHaveLength(1)
532 })
533​
534 expect(result.current.data[0]?.age).toBe(35)
535 })
536​
537 it(`should work with pre-created SingleResult collection`, async () => {
538 const collection = createCollection(
539 mockSyncCollectionOptions<Person>({
540 id: `test-persons-suspense-single`,
541 getKey: (person: Person) => person.id,
542 initialData: initialPersons,
543 }),
544 )
545​
546 // Pre-create a SingleResult live query collection
547 const singlePersonQuery = createLiveQueryCollection((q) =>
548 q
549 .from({ persons: collection })
550 .where(({ persons }) => eq(persons.id, `1`))
551 .findOne(),
552 )
553​
554 const { result } = renderHook(
555 () => useLiveSuspenseQuery(singlePersonQuery),
556 {
557 wrapper: SuspenseWrapper,
558 },
559 )
560​
561 await waitFor(() => {
562 expect(result.current.data).toBeDefined()
563 })
564​
565 expect(result.current.data).toMatchObject({
566 id: `1`,
567 name: `John Doe`,
568 age: 30,
569 })
570 })
571​
572 it(`should handle StrictMode double-invocation correctly`, async () => {
573 const collection = createCollection(
574 mockSyncCollectionOptions<Person>({
575 id: `test-persons-suspense-strict`,
576 getKey: (person: Person) => person.id,
577 initialData: initialPersons,
578 }),
579 )
580​
581 const StrictModeWrapper = ({ children }: { children: ReactNode }) => (
582 <StrictMode>
583 <Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
584 </StrictMode>
585 )
586​
587 const { result } = renderHook(
588 () => useLiveSuspenseQuery((q) => q.from({ persons: collection })),
589 {
590 wrapper: StrictModeWrapper,
591 },
592 )
593​
594 await waitFor(() => {
595 expect(result.current.data).toHaveLength(3)
596 })
597​
598 // Verify data is correct despite double-invocation
599 expect(result.current.data).toHaveLength(3)
600 expect(result.current.data[0]).toMatchObject({
601 id: `1`,
602 name: `John Doe`,
603 })
604 })
605​
606 it(`should not re-suspend after hasBeenReady when isLoadingSubset changes`, async () => {
607 // This test verifies that after the initial ready state is reached,
608 // subsequent isLoadingSubset changes don't cause re-suspension
609 // (stale-while-revalidate behavior, matching TanStack Query)
610​
611 const collection = createCollection(
612 mockSyncCollectionOptions<Person>({
613 id: `test-persons-suspense-on-demand`,
614 getKey: (person: Person) => person.id,
615 initialData: initialPersons,
616 }),
617 )
618​
619 let suspenseCount = 0
620​
621 const SuspenseTracker = ({ children }: { children: ReactNode }) => {
622 return (
623 <Suspense
624 fallback={
625 <div>
626 {(() => {
627 suspenseCount++
628 return `Loading...`
629 })()}
630 </div>
631 }
632 >
633 {children}
634 </Suspense>
635 )
636 }
637​
638 const { result } = renderHook(
639 () => {
640 return useLiveSuspenseQuery((q) => q.from({ persons: collection }))
641 },
642 {
643 wrapper: SuspenseTracker,
644 },
645 )
646​
647 // Wait for initial load
648 await waitFor(() => {
649 expect(result.current.data).toHaveLength(3)
650 })
651​
652 const initialSuspenseCount = suspenseCount
653​
654 // Now simulate on-demand loading by tracking a load promise on the live query collection
655 // This mimics what happens when a new subset query is made in on-demand mode
656 let resolveLoadPromise: () => void
657 const loadPromise = new Promise<void>((resolve) => {
658 resolveLoadPromise = resolve
659 })
660​
661 // Track the load promise on the LIVE QUERY collection - this sets isLoadingSubset = true
662 result.current.collection._sync.trackLoadPromise(loadPromise)
663​
664 // Verify isLoadingSubset is now true on the live query collection
665 expect(result.current.collection.isLoadingSubset).toBe(true)
666​
667 // The collection is still ready, but isLoadingSubset is true
668 expect(result.current.collection.status).toBe(`ready`)
669​
670 // Resolve the load promise to simulate data loading complete
671 resolveLoadPromise!()
672​
673 // Wait for the loadingSubset:change event to propagate
674 await waitFor(() => {
675 expect(result.current.collection.isLoadingSubset).toBe(false)
676 })
677​
678 // After hasBeenReadyRef is set, subsequent isLoadingSubset changes
679 // should NOT cause re-suspension (stale-while-revalidate behavior)
680 expect(suspenseCount).toBe(initialSuspenseCount)
681​
682 // Data should still be available
683 expect(result.current.data).toHaveLength(3)
684 })
685})