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

suspense-after-readiness.test.tsx

76 lines2.8 KB

1/**
2 * Suspense after initial-query readiness witness.
3 *
4 * Law (packages/db/src/query/live/ARCHITECTURE.md, law 16): after a live
5 * query's initial-query readiness, a source's sync problem leaves the query's
6 * status and rows alone and shows on the source's node. A Suspense boundary
7 * therefore keeps showing the rows: it does not fall back, and nothing throws.
8 * The shared conformance scenario `sync-errors-after-readiness` checks the
9 * same law for the hook without a Suspense boundary.
10 */
11import { describe, expect, it } from 'vitest'
12import { render, waitFor } from '@solidjs/testing-library'
13import { createCollection } from '@tanstack/db'
14import { Suspense } from 'solid-js'
15import { useLiveQuery } from '../src/useLiveQuery'
16import type { SyncConfig } from '@tanstack/db'
17​
18const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
19​
20type Post = { id: string; title: string }
21type SyncParams = Parameters<SyncConfig<Post, string | number>[`sync`]>[0]
22​
23describe(`useLiveQuery under Suspense after readiness`, () => {
24 it(`keeps the rows shown when the source reports a problem or stops`, async () => {
25 let params: SyncParams | undefined
26 const source = createCollection<Post>({
27 id: `solid-suspense-after-readiness`,
28 getKey: (post) => post.id,
29 sync: {
30 sync: (next) => {
31 params = next
32 next.begin()
33 next.write({ type: `insert`, value: { id: `p1`, title: `one` } })
34 next.commit()
35 next.markReady()
36 },
37 },
38 })
39 let status: (() => string) | undefined
40 let cleanupQuery: (() => Promise<void>) | undefined
41 function Title() {
42 const query = useLiveQuery((q) => q.from({ post: source }))
43 status = () => query.status
44 cleanupQuery = () => query.collection.cleanup()
45 return <div data-testid="title">{query()[0]?.title}</div>
46 }
47 const view = render(() => (
48 <Suspense fallback={<div data-testid="waiting">Waiting</div>}>
49 <Title />
50 </Suspense>
51 ))
52 try {
53 const title = await view.findByTestId(`title`)
54 expect(title.textContent).toBe(`one`)
55​
56 params!.reportError(new Error(`source problem`))
57 await flush()
58 expect(status!()).toBe(`ready`)
59 expect(source.health.failureReason?.message).toBe(`source problem`)
60 expect(view.queryByTestId(`waiting`)).toBeNull()
61 expect(view.getByTestId(`title`).textContent).toBe(`one`)
62​
63 params!.fail(new Error(`source gave up`))
64 await flush()
65 expect(status!()).toBe(`ready`)
66 expect(source.health.error?.message).toBe(`source gave up`)
67 expect(view.queryByTestId(`waiting`)).toBeNull()
68 expect(view.getByTestId(`title`).textContent).toBe(`one`)
69 } finally {
70 view.unmount()
71 await waitFor(() => expect(true).toBe(true))
72 await cleanupQuery?.()
73 await source.cleanup()
74 }
75 })
76})