Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { render, screen } from '@testing-library/react'
3import { DbClient, collectionOptions } from '@tanstack/db'
4import { DbProvider, useDbClient } from '../src/DbProvider'
5import { HydrationBoundary } from '../src/HydrationBoundary'
6
7type Person = {
8 id: string
9 name: string
10}
11
12const people = collectionOptions(`hydration-boundary-people`, () => ({
13 id: `hydration-boundary-people`,
14 getKey: (person: Person) => person.id,
15 sync: {
16 sync: ({ markReady }) => markReady(),
17 },
18}))
19
20const state = {
21 collections: [
22 {
23 collectionId: people.id,
24 rows: [{ key: `1`, value: { id: `1`, name: `Hydrated` } }],
25 },
26 ],
27}
28
29function PersonName() {
30 const client = useDbClient()
31 return <span>{client.collection(people).get(`1`)?.name}</span>
32}
33
34function App({ client }: { client: DbClient }) {
35 return (
36 <DbProvider client={client}>
37 <HydrationBoundary state={state}>
38 <PersonName />
39 </HydrationBoundary>
40 </DbProvider>
41 )
42}
43
44describe(`HydrationBoundary`, () => {
45 it(`hydrates before children render and follows the provider client`, () => {
46 const firstClient = new DbClient()
47 const firstHydrate = vi.spyOn(firstClient, `hydrate`)
48 const view = render(<App client={firstClient} />)
49
50 expect(screen.getByText(`Hydrated`)).toBeInTheDocument()
51 expect(firstHydrate).toHaveBeenCalledTimes(1)
52
53 view.rerender(<App client={firstClient} />)
54 expect(firstHydrate).toHaveBeenCalledTimes(1)
55
56 const secondClient = new DbClient()
57 const secondHydrate = vi.spyOn(secondClient, `hydrate`)
58 view.rerender(<App client={secondClient} />)
59
60 expect(screen.getByText(`Hydrated`)).toBeInTheDocument()
61 expect(secondHydrate).toHaveBeenCalledTimes(1)
62 })
63})