Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { flushSync } from 'svelte'
3import { createCollection, createLiveQueryCollection } from '@tanstack/db'
4import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery.svelte.js'
5import { mockSyncCollectionOptions } from '../../db/tests/utils'
6
7type Post = {
8 id: string
9 title: string
10 createdAt: number
11}
12
13function createPosts(count: number): Array<Post> {
14 return Array.from({ length: count }, (_, index) => ({
15 id: String(index + 1),
16 title: `Post ${index + 1}`,
17 createdAt: count - index,
18 }))
19}
20
21function createPostsCollection(id: string, count: number) {
22 return createCollection(
23 mockSyncCollectionOptions<Post>({
24 autoIndex: `eager`,
25 id,
26 getKey: (post) => post.id,
27 initialData: createPosts(count),
28 }),
29 )
30}
31
32function createPostsLiveQuery(posts: ReturnType<typeof createPostsCollection>) {
33 return createLiveQueryCollection({
34 query: (q) =>
35 q
36 .from({ posts })
37 .orderBy(({ posts: post }) => post.createdAt, `desc`)
38 .limit(4),
39 })
40}
41
42function usePostsCollectionInfiniteQuery(
43 getCollection: () => ReturnType<typeof createPostsLiveQuery>,
44) {
45 return useLiveInfiniteQuery(getCollection, { pageSize: 3 })
46}
47
48describe(`useLiveInfiniteQuery`, () => {
49 it(`rejects a server-page callback before constructing a query`, () => {
50 const queryFn = vi.fn(() => {
51 throw new Error(`query must not be constructed`)
52 })
53 const config = { pageSize: 2, getNextPageParam: () => 1 }
54 const stop = $effect.root(() => {
55 expect(() => useLiveInfiniteQuery(queryFn, config)).toThrow(
56 `getNextPageParam is not supported`,
57 )
58 expect(queryFn).not.toHaveBeenCalled()
59 })
60 stop()
61 })
62
63 let cleanup: (() => void) | undefined
64
65 afterEach(() => {
66 cleanup?.()
67 cleanup = undefined
68 vi.restoreAllMocks()
69 })
70
71 it(`accepts a reactive getter for a pre-created ordered collection`, async () => {
72 const posts = createPostsCollection(`svelte-infinite-precreated`, 7)
73 const livePosts = createLiveQueryCollection({
74 query: (q) =>
75 q
76 .from({ posts })
77 .orderBy(({ posts: post }) => post.createdAt, `desc`)
78 .limit(2)
79 .offset(1),
80 })
81 await livePosts.preload()
82 const warning = vi.spyOn(console, `warn`).mockImplementation(() => {})
83
84 let query!: ReturnType<typeof usePostsCollectionInfiniteQuery>
85 cleanup = $effect.root(() => {
86 query = useLiveInfiniteQuery(() => livePosts, {
87 pageSize: 3,
88 })
89 })
90 flushSync()
91 // flushSync starts the subscription but does not settle its window load.
92 await vi.waitFor(() =>
93 expect(livePosts.utils.getWindow()).toEqual({ offset: 0, limit: 4 }),
94 )
95 flushSync()
96
97 expect(query.collection).toBe(livePosts)
98 expect(query.data.map((post) => post.id)).toEqual([`1`, `2`, `3`])
99 expect(query.state.get(`1`)?.title).toBe(`Post 1`)
100 expect(query.hasNextPage).toBe(true)
101 expect(warning).toHaveBeenCalledOnce()
102 expect(livePosts.utils.getWindow()).toEqual({ offset: 0, limit: 4 })
103 })
104
105 it(`resets to the first page when a collection getter changes`, async () => {
106 const firstPosts = createPostsCollection(`svelte-infinite-swap-first`, 8)
107 const secondPosts = createPostsCollection(`svelte-infinite-swap-second`, 4)
108 const firstQuery = createPostsLiveQuery(firstPosts)
109 const secondQuery = createPostsLiveQuery(secondPosts)
110 await Promise.all([firstQuery.preload(), secondQuery.preload()])
111
112 let query: ReturnType<typeof usePostsCollectionInfiniteQuery> | undefined
113 let replaceCollection:
114 | ((collection: typeof secondQuery) => void)
115 | undefined
116 cleanup = $effect.root(() => {
117 let selectedQuery = $state(firstQuery)
118 query = usePostsCollectionInfiniteQuery(() => selectedQuery)
119 replaceCollection = (collection) => {
120 selectedQuery = collection
121 }
122 })
123 flushSync()
124 if (!query || !replaceCollection) {
125 throw new Error(`Failed to mount infinite query`)
126 }
127
128 await query.fetchNextPage()
129 flushSync()
130 expect(query.pages).toHaveLength(2)
131
132 replaceCollection(secondQuery)
133 flushSync()
134
135 expect(query.collection).toBe(secondQuery)
136 expect(query.pages).toHaveLength(1)
137 expect(query.data.map((post) => post.createdAt)).toEqual([4, 3, 2])
138 })
139})