Open History to see the last commit
1import { describe, expect, it, vi } from "vitest"
2import { act, renderHook } from "@testing-library/react"
3import mitt from "mitt"
4import { useCollection } from "../src/useCollection"
5import type { PendingMutation } from "@tanstack/optimistic"
6import "fake-indexeddb/auto"
7
8describe(`useCollection`, () => {
9 it(`should handle insert, update, and delete operations`, async () => {
10 const emitter = mitt()
11 const persistMock = vi.fn().mockResolvedValue(undefined)
12
13 // Setup initial hook render
14 const { result } = renderHook(() =>
15 useCollection<{ name: string }>({
16 id: `test-collection`,
17 sync: {
18 sync: ({ begin, write, commit }) => {
19 emitter.on(`*`, (_, mutations) => {
20 begin()
21 ;(mutations as Array<PendingMutation>).forEach((mutation) => {
22 write({
23 key: mutation.key,
24 type: mutation.type,
25 value: mutation.changes as { name: string },
26 })
27 })
28 commit()
29 })
30 },
31 },
32 mutationFn: {
33 persist: persistMock,
34 awaitSync: ({ transaction }) => {
35 act(() => {
36 emitter.emit(`update`, transaction.mutations)
37 })
38 return Promise.resolve()
39 },
40 },
41 })
42 )
43
44 // Initial state should be empty
45 expect(result.current.state.size).toBe(0)
46 expect(result.current.data).toEqual([])
47
48 // Test single insert with explicit key
49 await act(async () => {
50 await result.current.insert({ name: `Alice` }, { key: `user1` })
51 })
52
53 // Verify insert
54 expect(result.current.state.size).toBe(1)
55 expect(result.current.state.get(`user1`)).toEqual({ name: `Alice` })
56 expect(result.current.data).toEqual([{ name: `Alice` }])
57
58 // Test bulk insert with sparse keys
59 await act(async () => {
60 await result.current.insert([{ name: `Bob` }, { name: `Charlie` }], {
61 key: [`user2`, undefined],
62 })
63 })
64
65 // Get the auto-generated key for Charlie
66 const charlieKey = Array.from(result.current.state.keys())[2]
67
68 // Verify bulk insert
69 expect(result.current.state.size).toBe(3)
70 expect(result.current.state.get(`user2`)).toEqual({ name: `Bob` })
71 expect(result.current.state.get(charlieKey!)).toEqual({ name: `Charlie` })
72 expect(result.current.data.length).toBe(3)
73 expect(result.current.data).toContainEqual({ name: `Bob` })
74 expect(result.current.data).toContainEqual({ name: `Charlie` })
75
76 // Test update with callback
77 const updateTransaction = await act(async () => {
78 return await result.current.update(
79 result.current.state.get(`user1`)!,
80 (item) => {
81 item.name = `Alice Smith`
82 }
83 )
84 })
85
86 await act(async () => {
87 await updateTransaction.isSynced?.promise
88 })
89
90 // Verify update
91 expect(result.current.state.get(`user1`)).toEqual({ name: `Alice Smith` })
92 expect(result.current.data).toContainEqual({ name: `Alice Smith` })
93
94 // Test bulk update with metadata
95 await act(async () => {
96 const items = [
97 result.current.state.get(`user1`)!,
98 result.current.state.get(`user2`)!,
99 ]
100 return await result.current.update(
101 items,
102 { metadata: { bulkUpdate: true } },
103 (drafts) => {
104 drafts.forEach((draft, i) => {
105 if (i === 0) {
106 draft.name = draft.name + ` Jr.`
107 } else if (i === 1) {
108 draft.name = draft.name + ` Sr.`
109 }
110 })
111 }
112 )
113 })
114
115 // Verify bulk update
116 expect(result.current.state.get(`user1`)).toEqual({
117 name: `Alice Smith Jr.`,
118 })
119 expect(result.current.state.get(`user2`)).toEqual({ name: `Bob Sr.` })
120 expect(result.current.data).toContainEqual({ name: `Alice Smith Jr.` })
121 expect(result.current.data).toContainEqual({ name: `Bob Sr.` })
122
123 // Test single delete
124 await act(async () => {
125 await result.current.delete(result.current.state.get(`user1`)!)
126 })
127
128 // Verify single delete
129 expect(result.current.state.has(`user1`)).toBe(false)
130 expect(result.current.data).not.toContainEqual({ name: `Alice Smith Jr.` })
131
132 // Test bulk delete with metadata
133 await act(async () => {
134 const items = [
135 result.current.state.get(`user2`)!,
136 result.current.state.get(charlieKey!)!,
137 ]
138 await result.current.delete(items, {
139 metadata: { reason: `bulk cleanup` },
140 })
141 })
142
143 // Verify all items are deleted
144 expect(result.current.state.size).toBe(0)
145 expect(result.current.data.length).toBe(0)
146
147 // Verify persist was called for each operation
148 expect(persistMock).toHaveBeenCalledTimes(6) // 2 inserts + 2 updates + 2 deletes
149 })
150
151 it(`should expose state, items, and data properties correctly`, async () => {
152 const emitter = mitt()
153 const persistMock = vi.fn().mockResolvedValue(undefined)
154
155 // Setup initial hook render
156 const { result } = renderHook(() =>
157 useCollection({
158 id: `test-properties`,
159 mutationFn: {
160 persist: persistMock,
161 awaitSync: ({ transaction }) => {
162 act(() => {
163 emitter.emit(`update`, transaction.mutations)
164 })
165 return Promise.resolve()
166 },
167 },
168 sync: {
169 sync: ({ begin, write, commit }) => {
170 emitter.on(`*`, (_, mutations) => {
171 begin()
172 ;(mutations as Array<PendingMutation>).forEach((mutation) => {
173 write({
174 key: mutation.key,
175 type: mutation.type,
176 value: mutation.changes,
177 })
178 })
179 commit()
180 })
181 },
182 },
183 })
184 )
185
186 // Initial state should be empty
187 expect(result.current.state).toBeInstanceOf(Map)
188 expect(result.current.state.size).toBe(0)
189 expect(result.current.data).toBeInstanceOf(Array)
190 expect(result.current.data.length).toBe(0)
191
192 // Insert some test data
193 await act(async () => {
194 await result.current.insert(
195 [
196 { id: 1, name: `Item 1` },
197 { id: 2, name: `Item 2` },
198 { id: 3, name: `Item 3` },
199 ],
200 { key: [`key1`, `key2`, `key3`] }
201 )
202 emitter.emit(`update`, [
203 { key: `key1`, type: `insert`, changes: { id: 1, name: `Item 1` } },
204 { key: `key2`, type: `insert`, changes: { id: 2, name: `Item 2` } },
205 { key: `key3`, type: `insert`, changes: { id: 3, name: `Item 3` } },
206 ])
207 })
208
209 // Verify state property (Map)
210 expect(result.current.state.size).toBe(3)
211 expect(result.current.state.get(`key1`)).toEqual({ id: 1, name: `Item 1` })
212 expect(result.current.state.get(`key2`)).toEqual({ id: 2, name: `Item 2` })
213 expect(result.current.state.get(`key3`)).toEqual({ id: 3, name: `Item 3` })
214
215 // Verify items property (Array)
216 expect(result.current.data.length).toBe(3)
217 expect(result.current.data).toContainEqual({ id: 1, name: `Item 1` })
218 expect(result.current.data).toContainEqual({ id: 2, name: `Item 2` })
219 expect(result.current.data).toContainEqual({ id: 3, name: `Item 3` })
220 })
221
222 it(`should work with a selector function`, async () => {
223 const emitter = mitt()
224 const persistMock = vi.fn().mockResolvedValue(undefined)
225
226 // Setup hook with selector
227 const { result } = renderHook(() =>
228 useCollection<{ id: number; name: string }>({
229 id: `test-selector`,
230 mutationFn: {
231 persist: persistMock,
232 awaitSync: ({ transaction }) => {
233 act(() => {
234 emitter.emit(`update`, transaction.mutations)
235 })
236 return Promise.resolve()
237 },
238 },
239 sync: {
240 sync: ({ begin, write, commit }) => {
241 emitter.on(`*`, (_, mutations) => {
242 begin()
243 ;(mutations as Array<PendingMutation>).forEach((mutation) => {
244 write({
245 key: mutation.key,
246 type: mutation.type,
247 // TODO this should get the type automatically
248 value: mutation.changes as { id: number; name: string },
249 })
250 })
251 commit()
252 })
253 },
254 },
255 })
256 )
257
258 // Initial state
259 expect(result.current.state).toBeInstanceOf(Map)
260 expect(result.current.state.size).toBe(0)
261 expect(result.current.data).toBeInstanceOf(Array)
262 expect(result.current.data.length).toBe(0)
263
264 // Insert some test data
265 await act(async () => {
266 await result.current.insert(
267 [
268 { id: 1, name: `Alice` },
269 { id: 2, name: `Bob` },
270 { id: 3, name: `Charlie` },
271 ],
272 { key: [`key1`, `key2`, `key3`] }
273 )
274 emitter.emit(`update`, [
275 { key: `key1`, type: `insert`, changes: { id: 1, name: `Alice` } },
276 { key: `key2`, type: `insert`, changes: { id: 2, name: `Bob` } },
277 { key: `key3`, type: `insert`, changes: { id: 3, name: `Charlie` } },
278 ])
279 })
280
281 // Verify selector result
282 expect(
283 result.current.data.map((item) => (item as { name: string }).name)
284 ).toEqual([`Alice`, `Bob`, `Charlie`])
285
286 // Verify state and data are still available
287 expect(result.current.state.size).toBe(3)
288 expect(result.current.data.length).toBe(3)
289 })
290})