Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2
3import { renderHook } from '@testing-library/react'
4import { createCollection, createLiveQueryCollection } from '@tanstack/db'
5import { useLiveQuery } from '../src/useLiveQuery'
6import { mockSyncCollectionOptions } from '../../db/tests/utils'
7import type * as ReactNS from 'react'
8
9// Intercept React.useSyncExternalStore so we can capture the `subscribe`
10// callback that `useLiveQuery` registers and assert that it does not invoke
11// `onStoreChange` synchronously when the collection is already ready.
12let capturedSubscribe: ((cb: () => void) => () => void) | null = null
13
14vi.mock('react', async () => {
15 const actual = await vi.importActual<typeof ReactNS>('react')
16 return {
17 ...actual,
18 default: (actual as any).default ?? actual,
19 useSyncExternalStore: (subscribe: any, getSnapshot: any) => {
20 capturedSubscribe = subscribe
21 return getSnapshot()
22 },
23 }
24})
25
26type Person = { id: string; name: string; age: number }
27
28const initialPersons: Array<Person> = [
29 { id: `1`, name: `A`, age: 10 },
30 { id: `2`, name: `B`, age: 20 },
31]
32
33describe(`useLiveQuery: eager onStoreChange must not fire synchronously during subscribe`, () => {
34 it(`defers the initial ready-state onStoreChange to a microtask`, async () => {
35 const base = createCollection(
36 mockSyncCollectionOptions<Person>({
37 id: `eager-onstorechange-persons`,
38 getKey: (p) => p.id,
39 initialData: initialPersons,
40 }),
41 )
42
43 const lqc = createLiveQueryCollection({
44 startSync: true,
45 query: (q) => q.from({ persons: base }),
46 })
47 await lqc.preload()
48 expect(lqc.status).toBe(`ready`)
49
50 capturedSubscribe = null
51 renderHook(() => useLiveQuery(lqc))
52 expect(capturedSubscribe).toBeTypeOf(`function`)
53
54 const onStoreChange = vi.fn()
55 const unsub = capturedSubscribe!(onStoreChange)
56
57 // onStoreChange must not be invoked synchronously inside subscribe —
58 // useSyncExternalStore's own post-subscribe getSnapshot re-read covers a
59 // ready transition that happened between render and subscribe, so an
60 // already-ready unchanged collection needs no wake-up at all.
61 expect(onStoreChange).not.toHaveBeenCalled()
62
63 await Promise.resolve()
64 expect(onStoreChange).not.toHaveBeenCalled()
65
66 // A real delta does wake the store.
67 base.utils.begin()
68 base.utils.write({
69 type: `insert`,
70 value: { id: `3`, name: `C`, age: 30 },
71 })
72 base.utils.commit()
73 await Promise.resolve()
74 expect(onStoreChange).toHaveBeenCalled()
75
76 unsub()
77 })
78})