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

useLiveQuery.test.ts

165 lines5.5 KB

1/**
2 * Preact-specific binding witnesses for `useLiveQuery`.
3 *
4 * The shared conformance suite owns the cross-framework result and identity
5 * laws. These witnesses cover Preact binding obligations its histories cannot
6 * reach:
7 *
8 * - A publication between render and subscription is not lost. A sibling's
9 * layout effect can write to the source after this hook rendered but before
10 * it subscribed; the committed result must include that write.
11 * - Identity comes from the query IR or from `queryKey`, as in React. A
12 * changed key recompiles the query, and an equal key keeps its live-query
13 * Collection. A structurally equal rerender keeps it too.
14 *
15 * Observation: each component records the rows it rendered. Preact commits a
16 * render synchronously, so the last render is the committed result.
17 */
18import { Fragment, h, render } from 'preact'
19import { useLayoutEffect } from 'preact/hooks'
20import { act } from 'preact/test-utils'
21import { createCollection, eq } from '@tanstack/db'
22import { afterEach, describe, expect, it } from 'vitest'
23import { mockSyncCollectionOptions } from '../../db/tests/utils'
24import { useLiveQuery } from '../src/useLiveQuery'
25import type { ComponentChild } from 'preact'
26​
27type Row = { id: string; team: string }
28​
29const containers: Array<HTMLElement> = []
30​
31function mountRoot(vnode: ComponentChild): HTMLElement {
32 const container = document.createElement(`div`)
33 containers.push(container)
34 act(() => render(vnode, container))
35 return container
37​
38afterEach(() => {
39 for (const container of containers.splice(0)) {
40 act(() => render(null, container))
41 }
42})
43​
44function makeSource(id: string, rows: Array<Row>) {
45 return createCollection(
46 mockSyncCollectionOptions<Row>({
47 id,
48 getKey: (row) => row.id,
49 initialData: rows,
50 }),
51 )
53​
54async function settle() {
55 await act(async () => {
56 await new Promise((resolve) => setTimeout(resolve, 0))
57 })
59​
60describe(`useLiveQuery subscription`, () => {
61 it(`publishes a write made between render and subscription`, async () => {
62 const source = makeSource(`late-write`, [{ id: `a`, team: `x` }])
63 let rendered: Array<string> = []
64 // Preact renders the whole tree before it runs layout effects, and runs
65 // sibling layout effects in render order. Placed first, this write lands
66 // after Reader rendered and before Reader's subscription effect runs.
67 function Writer() {
68 useLayoutEffect(() => {
69 source.utils.begin()
70 source.utils.write({ type: `insert`, value: { id: `b`, team: `x` } })
71 source.utils.commit()
72 }, [])
73 return null
74 }
75 function Reader() {
76 const { data } = useLiveQuery((q) => q.from({ row: source }))
77 rendered = data.map((row) => row.id)
78 return null
79 }
80​
81 mountRoot(h(Fragment, null, h(Writer, null), h(Reader, null)))
82 await settle()
83 expect(rendered).toEqual([`a`, `b`])
84 })
85})
86​
87describe(`useLiveQuery identity`, () => {
88 it(`keeps a structurally equal query across rerenders`, async () => {
89 const source = makeSource(`structural`, [
90 { id: `a`, team: `x` },
91 { id: `b`, team: `y` },
92 ])
93 let collection: unknown
94 function Reader({ team }: { team: string }) {
95 const result = useLiveQuery((q) =>
96 q.from({ row: source }).where(({ row }) => eq(row.team, team)),
97 )
98 collection = result.collection
99 return null
100 }
101 const container = mountRoot(h(Reader, { team: `x` }))
102 await settle()
103 const first = collection
104 act(() => render(h(Reader, { team: `x` }), container))
105 expect(collection).toBe(first)
106 act(() => render(h(Reader, { team: `y` }), container))
107 expect(collection).not.toBe(first)
108 })
109​
110 it(`recompiles a functional query when its queryKey changes`, async () => {
111 const source = makeSource(`functional-key`, [
112 { id: `a`, team: `x` },
113 { id: `b`, team: `y` },
114 ])
115 let rendered: Array<string> = []
116 let collection: unknown
117 function Reader({ team }: { team: string }) {
118 const result = useLiveQuery({
119 queryKey: [`team`, team],
120 query: (q) =>
121 q.from({ row: source }).fn.where(({ row }) => row.team === team),
122 })
123 rendered = result.data.map((row) => row.id)
124 collection = result.collection
125 return null
126 }
127​
128 const container = mountRoot(h(Reader, { team: `x` }))
129 await settle()
130 expect(rendered).toEqual([`a`])
131 const first = collection
132​
133 act(() => render(h(Reader, { team: `x` }), container))
134 await settle()
135 expect(collection).toBe(first)
136​
137 act(() => render(h(Reader, { team: `y` }), container))
138 await settle()
139 expect(rendered).toEqual([`b`])
140 expect(collection).not.toBe(first)
141 })
142​
143 // A nonempty queryKey owns the identity, so the hook claims no source IDs.
144 it(`lets a keyed query swap a source under its ID when the key changes`, async () => {
145 const first = makeSource(`keyed-swap`, [{ id: `a`, team: `x` }])
146 const replacement = makeSource(`keyed-swap`, [{ id: `b`, team: `x` }])
147 let rendered: Array<string> = []
148 function Reader({ source }: { source: typeof first }) {
149 const result = useLiveQuery({
150 queryKey: [`keyed-swap`, source === first ? 1 : 2],
151 query: (q) => q.from({ row: source }),
152 })
153 rendered = result.data.map((row) => row.id)
154 return null
155 }
156​
157 const container = mountRoot(h(Reader, { source: first }))
158 await settle()
159 expect(rendered).toEqual([`a`])
160​
161 act(() => render(h(Reader, { source: replacement }), container))
162 await settle()
163 expect(rendered).toEqual([`b`])
164 })
165})