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

useLiveInfiniteQuery.svelte.test.ts

266 lines8.4 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { flushSync } from 'svelte'
3import {
4 BTreeIndex,
5 createCollection,
6 createLiveQueryCollection,
7 lte,
8} from '@tanstack/db'
9import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery.svelte.js'
10import { useLiveQuery } from '../src/useLiveQuery.svelte.js'
11import { mockSyncCollectionOptions } from '../../db/tests/utils'
12import type { InitialQueryBuilder } from '@tanstack/db'
13​
14type Post = {
15 id: string
16 title: string
17 createdAt: number
19​
20function createPosts(count: number): Array<Post> {
21 return Array.from({ length: count }, (_, index) => ({
22 id: String(index + 1),
23 title: `Post ${index + 1}`,
24 createdAt: count - index,
25 }))
27​
28function createPostsCollection(id: string, count: number) {
29 return createCollection(
30 mockSyncCollectionOptions<Post>({
31 autoIndex: `eager`,
32 id,
33 getKey: (post) => post.id,
34 initialData: createPosts(count),
35 }),
36 )
38​
39function createPostsLiveQuery(posts: ReturnType<typeof createPostsCollection>) {
40 return createLiveQueryCollection({
41 query: (q) =>
42 q
43 .from({ posts })
44 .orderBy(({ posts: post }) => post.createdAt, `desc`)
45 .limit(4),
46 })
48​
49// An on-demand source that counts acquisitions. Its loads never settle, so
50// the test observes only whether a request was sent.
51function createCountingOnDemandPosts(id: string) {
52 let loads = 0
53 const posts = createCollection<Post>({
54 id,
55 getKey: (post) => post.id,
56 syncMode: `on-demand`,
57 autoIndex: `eager`,
58 defaultIndexType: BTreeIndex,
59 sync: {
60 sync: ({ markReady }) => {
61 markReady()
62 return {
63 loadSubset: () => {
64 loads++
65 return new Promise<void>(() => {})
66 },
67 }
68 },
69 },
70 })
71 return { posts, loads: () => loads }
73​
74// Reads the maximum inside the query callback, so the hook tracks it directly.
75function usePostsAtMostInfiniteQuery(
76 posts: ReturnType<typeof createPostsCollection>,
77 getMaximum: () => number,
78) {
79 return useLiveInfiniteQuery(
80 (q: InitialQueryBuilder) =>
81 q
82 .from({ posts })
83 .where(({ posts: post }) => lte(post.createdAt, getMaximum()))
84 .orderBy(({ posts: post }) => post.createdAt, `desc`),
85 { pageSize: 3 },
86 )
88​
89function usePostsCollectionInfiniteQuery(
90 getCollection: () => ReturnType<typeof createPostsLiveQuery>,
91) {
92 return useLiveInfiniteQuery(getCollection, { pageSize: 3 })
94​
95describe(`useLiveInfiniteQuery`, () => {
96 it(`rejects a server-page callback before constructing a query`, () => {
97 const queryFn = vi.fn(() => {
98 throw new Error(`query must not be constructed`)
99 })
100 const config = { pageSize: 2, getNextPageParam: () => 1 }
101 const stop = $effect.root(() => {
102 expect(() => useLiveInfiniteQuery(queryFn, config)).toThrow(
103 `getNextPageParam is not supported`,
104 )
105 expect(queryFn).not.toHaveBeenCalled()
106 })
107 stop()
108 })
109​
110 let cleanup: (() => void) | undefined
111​
112 afterEach(() => {
113 cleanup?.()
114 cleanup = undefined
115 vi.restoreAllMocks()
116 })
117​
118 it(`accepts a reactive getter for a pre-created ordered collection`, async () => {
119 const posts = createPostsCollection(`svelte-infinite-precreated`, 7)
120 const livePosts = createLiveQueryCollection({
121 query: (q) =>
122 q
123 .from({ posts })
124 .orderBy(({ posts: post }) => post.createdAt, `desc`)
125 .limit(2)
126 .offset(1),
127 })
128 await livePosts.preload()
129 const warning = vi.spyOn(console, `warn`).mockImplementation(() => {})
130​
131 let query!: ReturnType<typeof usePostsCollectionInfiniteQuery>
132 cleanup = $effect.root(() => {
133 query = useLiveInfiniteQuery(() => livePosts, {
134 pageSize: 3,
135 })
136 })
137 flushSync()
138 // flushSync starts the subscription but does not settle its window load.
139 await vi.waitFor(() =>
140 expect(livePosts.utils.getWindow()).toEqual({ offset: 0, limit: 4 }),
141 )
142 flushSync()
143​
144 expect(query.collection).toBe(livePosts)
145 expect(query.data.map((post) => post.id)).toEqual([`1`, `2`, `3`])
146 expect(query.state.get(`1`)?.title).toBe(`Post 1`)
147 expect(query.hasNextPage).toBe(true)
148 expect(warning).toHaveBeenCalledOnce()
149 expect(livePosts.utils.getWindow()).toEqual({ offset: 0, limit: 4 })
150 })
151​
152 it(`resets to the first page when a collection getter changes`, async () => {
153 const firstPosts = createPostsCollection(`svelte-infinite-swap-first`, 8)
154 const secondPosts = createPostsCollection(`svelte-infinite-swap-second`, 4)
155 const firstQuery = createPostsLiveQuery(firstPosts)
156 const secondQuery = createPostsLiveQuery(secondPosts)
157 await Promise.all([firstQuery.preload(), secondQuery.preload()])
158​
159 let query: ReturnType<typeof usePostsCollectionInfiniteQuery> | undefined
160 let replaceCollection:
161 ((collection: typeof secondQuery) => void) | undefined
162 cleanup = $effect.root(() => {
163 let selectedQuery = $state(firstQuery)
164 query = usePostsCollectionInfiniteQuery(() => selectedQuery)
165 replaceCollection = (collection) => {
166 selectedQuery = collection
167 }
168 })
169 flushSync()
170 if (!query || !replaceCollection) {
171 throw new Error(`Failed to mount infinite query`)
172 }
173​
174 await query.fetchNextPage()
175 flushSync()
176 expect(query.pages).toHaveLength(2)
177​
178 replaceCollection(secondQuery)
179 flushSync()
180​
181 expect(query.collection).toBe(secondQuery)
182 expect(query.pages).toHaveLength(1)
183 expect(query.data.map((post) => post.createdAt)).toEqual([4, 3, 2])
184 })
185​
186 it(`rebuilds the query when state read inside the query callback changes`, () => {
187 const posts = createPostsCollection(`svelte-infinite-tracked-read`, 8)
188 let query: ReturnType<typeof usePostsAtMostInfiniteQuery> | undefined
189 let setMaximum: ((maximum: number) => void) | undefined
190 cleanup = $effect.root(() => {
191 // No deps array: the derived controller tracks this read directly.
192 let maximum = $state(8)
193 query = usePostsAtMostInfiniteQuery(posts, () => maximum)
194 setMaximum = (next) => {
195 maximum = next
196 }
197 })
198 flushSync()
199 if (!query || !setMaximum) throw new Error(`Failed to mount infinite query`)
200 expect(query.data.map((post) => post.createdAt)).toEqual([8, 7, 6])
201​
202 setMaximum(5)
203 flushSync()
204 expect(query.data.map((post) => post.createdAt)).toEqual([5, 4, 3])
205 })
206 it(`acquires an on-demand source as often as useLiveQuery does after construction and a superseded recompute`, () => {
207 // The two hooks must behave the same. For each history, count source
208 // acquisitions once the subscribing effect has run, under each hook. The
209 // moment inside that tick differs: useLiveQuery rebuilds when its data is
210 // read, and this hook rebuilds when its effect runs. Only the settled count
211 // is compared.
212 const acquisitions = (hook: `live` | `infinite`, wrapped: boolean) => {
213 const { posts: remote, loads } = createCountingOnDemandPosts(
214 `svelte-parity-${hook}-${wrapped ? `wrapped` : `direct`}`,
215 )
216 // A live-query Collection does not copy its source's sync mode.
217 const posts: any = wrapped
218 ? createLiveQueryCollection({
219 query: (q) =>
220 q
221 .from({ posts: remote })
222 .orderBy(({ posts: post }) => post.createdAt, `desc`),
223 startSync: false,
224 gcTime: 1,
225 })
226 : remote
227 let read: (() => unknown) | undefined
228 let setMaximum: ((maximum: number) => void) | undefined
229 const stop = $effect.root(() => {
230 let maximum = $state(8)
231 if (hook === `infinite`) {
232 const query = usePostsAtMostInfiniteQuery(posts, () => maximum)
233 read = () => query.data
234 } else {
235 // useLiveQuery reads the infinite hook's first window.
236 const query = useLiveQuery((q: InitialQueryBuilder) =>
237 q
238 .from({ posts })
239 .where(({ posts: post }: any) => lte(post.createdAt, maximum))
240 .orderBy(({ posts: post }: any) => post.createdAt, `desc`)
241 .limit(4),
242 )
243 read = () => query.data
244 }
245 setMaximum = (next) => {
246 maximum = next
247 }
248 })
249 try {
250 read!()
251 setMaximum!(5)
252 read!()
253 flushSync()
254 return loads()
255 } finally {
256 stop()
257 }
258 }
259​
260 for (const wrapped of [false, true]) {
261 expect(acquisitions(`infinite`, wrapped)).toEqual(
262 acquisitions(`live`, wrapped),
263 )
264 }
265 })
266})