Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { act, renderHook } from '@testing-library/react'
3import {
4 createCollection,
5 debounceStrategy,
6 queueStrategy,
7 throttleStrategy,
8} from '@tanstack/db'
9import { usePacedMutations } from '../src/usePacedMutations'
10import { mockSyncCollectionOptionsNoInitialState } from '../../db/tests/utils'
11
12type Item = {
13 id: number
14 value: number
15}
16
17describe(`usePacedMutations React hook`, () => {
18 it(`should work with debounce strategy (smoke test)`, async () => {
19 const mutationFn = vi.fn(async () => {})
20
21 const collection = createCollection(
22 mockSyncCollectionOptionsNoInitialState<Item>({
23 id: `test`,
24 getKey: (item) => item.id,
25 }),
26 )
27
28 const preloadPromise = collection.preload()
29 collection.utils.begin()
30 collection.utils.commit()
31 collection.utils.markReady()
32 await preloadPromise
33
34 const { result } = renderHook(() =>
35 usePacedMutations<Item>({
36 onMutate: (item) => {
37 collection.insert(item)
38 },
39 mutationFn,
40 strategy: debounceStrategy({ wait: 50 }),
41 }),
42 )
43
44 let tx
45 act(() => {
46 tx = result.current({ id: 1, value: 1 })
47 })
48
49 expect(mutationFn).not.toHaveBeenCalled()
50
51 await new Promise((resolve) => setTimeout(resolve, 100))
52
53 expect(mutationFn).toHaveBeenCalledTimes(1)
54 expect(tx!.state).toBe(`completed`)
55 })
56
57 it(`should work with throttle strategy (smoke test)`, async () => {
58 const mutationFn = vi.fn(async () => {})
59
60 const collection = createCollection(
61 mockSyncCollectionOptionsNoInitialState<Item>({
62 id: `test`,
63 getKey: (item) => item.id,
64 }),
65 )
66
67 const preloadPromise = collection.preload()
68 collection.utils.begin()
69 collection.utils.commit()
70 collection.utils.markReady()
71 await preloadPromise
72
73 const { result } = renderHook(() =>
74 usePacedMutations<Item>({
75 onMutate: (item) => {
76 collection.insert(item)
77 },
78 mutationFn,
79 strategy: throttleStrategy({ wait: 50, leading: true }),
80 }),
81 )
82
83 let tx
84 act(() => {
85 tx = result.current({ id: 1, value: 1 })
86 })
87
88 await new Promise((resolve) => setTimeout(resolve, 10))
89 expect(mutationFn).toHaveBeenCalledTimes(1)
90 expect(tx!.state).toBe(`completed`)
91 })
92
93 it(`should work with queue strategy (smoke test)`, async () => {
94 const mutationFn = vi.fn(async () => {
95 await new Promise((resolve) => setTimeout(resolve, 5))
96 })
97
98 const collection = createCollection(
99 mockSyncCollectionOptionsNoInitialState<Item>({
100 id: `test`,
101 getKey: (item) => item.id,
102 }),
103 )
104
105 const preloadPromise = collection.preload()
106 collection.utils.begin()
107 collection.utils.commit()
108 collection.utils.markReady()
109 await preloadPromise
110
111 const { result } = renderHook(() =>
112 usePacedMutations<Item>({
113 onMutate: (item) => {
114 collection.insert(item)
115 },
116 mutationFn,
117 strategy: queueStrategy({ wait: 10 }),
118 }),
119 )
120
121 let tx
122 act(() => {
123 tx = result.current({ id: 1, value: 1 })
124 })
125
126 await tx!.isPersisted.promise
127 expect(mutationFn).toHaveBeenCalledTimes(1)
128 expect(tx!.state).toBe(`completed`)
129 })
130
131 describe(`memoization`, () => {
132 it(`should not recreate instance when strategy object changes but values are same`, () => {
133 const mutationFn = vi.fn(async () => {})
134 const onMutate = vi.fn(() => {})
135
136 // Simulate a custom hook that creates strategy inline on each render
137 const useCustomHook = (wait: number) => {
138 return usePacedMutations({
139 onMutate,
140 mutationFn,
141 // Strategy is created inline on every render - new object reference each time
142 strategy: debounceStrategy({ wait }),
143 })
144 }
145
146 const { result, rerender } = renderHook(
147 ({ wait }) => useCustomHook(wait),
148 {
149 initialProps: { wait: 3000 },
150 },
151 )
152
153 const firstMutate = result.current
154
155 // Rerender with same wait value - strategy object will be different reference
156 rerender({ wait: 3000 })
157 const secondMutate = result.current
158
159 // mutate function should be stable (same reference)
160 expect(secondMutate).toBe(firstMutate)
161
162 // Rerender with different wait value - should create new instance
163 rerender({ wait: 5000 })
164 const thirdMutate = result.current
165
166 // mutate function should be different now
167 expect(thirdMutate).not.toBe(firstMutate)
168 })
169
170 it(`should not recreate instance when wrapped in custom hook with inline strategy`, () => {
171 const mutationFn = vi.fn(async () => {})
172 const onMutate = vi.fn(() => {})
173
174 // Simulate the exact user scenario: custom hook wrapping usePacedMutations
175 const useDebouncedTransaction = (opts?: {
176 wait?: number
177 trailing?: boolean
178 leading?: boolean
179 }) => {
180 return usePacedMutations({
181 onMutate,
182 mutationFn,
183 strategy: debounceStrategy({
184 wait: opts?.wait ?? 3000,
185 trailing: opts?.trailing ?? true,
186 leading: opts?.leading ?? false,
187 }),
188 })
189 }
190
191 const { result, rerender } = renderHook(() => useDebouncedTransaction())
192
193 const firstMutate = result.current
194
195 // Multiple rerenders with no options - should not recreate instance
196 rerender()
197 expect(result.current).toBe(firstMutate)
198
199 rerender()
200 expect(result.current).toBe(firstMutate)
201
202 rerender()
203 expect(result.current).toBe(firstMutate)
204
205 // All should still be the same mutate function
206 expect(result.current).toBe(firstMutate)
207 })
208
209 it(`should recreate instance when strategy options actually change`, () => {
210 const mutationFn = vi.fn(async () => {})
211 const onMutate = vi.fn(() => {})
212
213 const useDebouncedTransaction = (opts?: {
214 wait?: number
215 trailing?: boolean
216 leading?: boolean
217 }) => {
218 return usePacedMutations({
219 onMutate,
220 mutationFn,
221 strategy: debounceStrategy({
222 wait: opts?.wait ?? 3000,
223 trailing: opts?.trailing ?? true,
224 leading: opts?.leading ?? false,
225 }),
226 })
227 }
228
229 const { result, rerender } = renderHook(
230 ({ opts }) => useDebouncedTransaction(opts),
231 { initialProps: { opts: { wait: 3000 } } },
232 )
233
234 const firstMutate = result.current
235
236 // Rerender with different wait value
237 rerender({ opts: { wait: 5000 } })
238 const secondMutate = result.current
239
240 // Should be different instance since wait changed
241 expect(secondMutate).not.toBe(firstMutate)
242
243 // Rerender with same wait value again
244 rerender({ opts: { wait: 5000 } })
245 const thirdMutate = result.current
246
247 // Should be same as second since value didn't change
248 expect(thirdMutate).toBe(secondMutate)
249 })
250 })
251})