Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { StrictMode } from 'react'
3import { act, renderHook, waitFor } from '@testing-library/react'
4import { createCollection } from '@tanstack/db'
5import { useLiveQuery } from '../src/useLiveQuery'
6import { mockSyncCollectionOptions } from '../../db/tests/utils'
7
8type Person = { id: string; name: string }
9
10describe(`useLiveQuery under StrictMode`, () => {
11 it(`keeps the subscription alive across StrictMode effect replay`, async () => {
12 const collection = createCollection(
13 mockSyncCollectionOptions<Person>({
14 id: `strictmode-persons`,
15 getKey: (p) => p.id,
16 initialData: [{ id: `1`, name: `A` }],
17 }),
18 )
19
20 // StrictMode double-invokes effects (mount → cleanup → mount). A dispose in
21 // the unmount effect would tear the observer down and never recreate it,
22 // leaving a dead subscription.
23 const { result } = renderHook(
24 () =>
25 useLiveQuery((q) =>
26 q
27 .from({ p: collection })
28 .select(({ p }) => ({ id: p.id, name: p.name })),
29 ),
30 { wrapper: StrictMode },
31 )
32
33 await waitFor(() => expect(result.current.data).toHaveLength(1))
34
35 // A mutation after the StrictMode replay must still reach the hook.
36 act(() => {
37 collection.utils.begin()
38 collection.utils.write({ type: `insert`, value: { id: `2`, name: `B` } })
39 collection.utils.commit()
40 })
41
42 await waitFor(() => expect(result.current.data).toHaveLength(2))
43 })
44})