Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

mutationCache.test.tsx

384 lines11.3 KB

1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { MutationCache, MutationObserver } from '..'
3import { createQueryClient, executeMutation, queryKey, sleep } from './utils'
4​
5describe('mutationCache', () => {
6 beforeEach(() => {
7 vi.useFakeTimers()
8 })
9​
10 afterEach(() => {
11 vi.useRealTimers()
12 })
13​
14 describe('MutationCacheConfig error callbacks', () => {
15 test('should call onError and onSettled when a mutation errors', async () => {
16 const key = queryKey()
17 const onError = vi.fn()
18 const onSuccess = vi.fn()
19 const onSettled = vi.fn()
20 const testCache = new MutationCache({ onError, onSuccess, onSettled })
21 const testClient = createQueryClient({ mutationCache: testCache })
22​
23 try {
24 await executeMutation(
25 testClient,
26 {
27 mutationKey: key,
28 mutationFn: () => Promise.reject(new Error('error')),
29 onMutate: () => 'context',
30 },
31 'vars',
32 )
33 } catch {}
34​
35 const mutation = testCache.getAll()[0]
36 expect(onError).toHaveBeenCalledTimes(1)
37 expect(onError).toHaveBeenCalledWith(
38 new Error('error'),
39 'vars',
40 'context',
41 mutation,
42 )
43 expect(onSuccess).not.toHaveBeenCalled()
44 expect(onSettled).toHaveBeenCalledTimes(1)
45 expect(onSettled).toHaveBeenCalledWith(
46 undefined,
47 new Error('error'),
48 'vars',
49 'context',
50 mutation,
51 )
52 })
53​
54 test('should be awaited', async () => {
55 const key = queryKey()
56 const states: Array<number> = []
57 const onError = async () => {
58 states.push(1)
59 await vi.advanceTimersByTimeAsync(1)
60 states.push(2)
61 }
62 const onSettled = async () => {
63 states.push(5)
64 await vi.advanceTimersByTimeAsync(1)
65 states.push(6)
66 }
67 const testCache = new MutationCache({ onError, onSettled })
68 const testClient = createQueryClient({ mutationCache: testCache })
69​
70 try {
71 await executeMutation(
72 testClient,
73 {
74 mutationKey: key,
75 mutationFn: () => Promise.reject(new Error('error')),
76 onError: async () => {
77 states.push(3)
78 await vi.advanceTimersByTimeAsync(1)
79 states.push(4)
80 },
81 onSettled: async () => {
82 states.push(7)
83 await vi.advanceTimersByTimeAsync(1)
84 states.push(8)
85 },
86 },
87 'vars',
88 )
89 } catch {}
90​
91 await vi.runAllTimersAsync()
92 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
93 })
94 })
95 describe('MutationCacheConfig success callbacks', () => {
96 test('should call onSuccess and onSettled when a mutation is successful', async () => {
97 const key = queryKey()
98 const onError = vi.fn()
99 const onSuccess = vi.fn()
100 const onSettled = vi.fn()
101 const testCache = new MutationCache({ onError, onSuccess, onSettled })
102 const testClient = createQueryClient({ mutationCache: testCache })
103​
104 try {
105 await executeMutation(
106 testClient,
107 {
108 mutationKey: key,
109 mutationFn: () => Promise.resolve({ data: 5 }),
110 onMutate: () => 'context',
111 },
112 'vars',
113 )
114 } catch {}
115​
116 const mutation = testCache.getAll()[0]
117 expect(onSuccess).toHaveBeenCalledTimes(1)
118 expect(onSuccess).toHaveBeenCalledWith(
119 { data: 5 },
120 'vars',
121 'context',
122 mutation,
123 )
124 expect(onError).not.toHaveBeenCalled()
125 expect(onSettled).toHaveBeenCalledTimes(1)
126 expect(onSettled).toHaveBeenCalledWith(
127 { data: 5 },
128 null,
129 'vars',
130 'context',
131 mutation,
132 )
133 })
134 test('should be awaited', async () => {
135 const key = queryKey()
136 const states: Array<number> = []
137 const onSuccess = async () => {
138 states.push(1)
139 await sleep(1)
140 states.push(2)
141 }
142 const onSettled = async () => {
143 states.push(5)
144 await sleep(1)
145 states.push(6)
146 }
147 const testCache = new MutationCache({ onSuccess, onSettled })
148 const testClient = createQueryClient({ mutationCache: testCache })
149​
150 executeMutation(
151 testClient,
152 {
153 mutationKey: key,
154 mutationFn: () => Promise.resolve({ data: 5 }),
155 onSuccess: async () => {
156 states.push(3)
157 await sleep(1)
158 states.push(4)
159 },
160 onSettled: async () => {
161 states.push(7)
162 await sleep(1)
163 states.push(8)
164 },
165 },
166 'vars',
167 )
168 await vi.runAllTimersAsync()
169​
170 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
171 })
172 })
173 describe('MutationCacheConfig.onMutate', () => {
174 test('should be called before a mutation executes', async () => {
175 const key = queryKey()
176 const onMutate = vi.fn()
177 const testCache = new MutationCache({ onMutate })
178 const testClient = createQueryClient({ mutationCache: testCache })
179​
180 try {
181 await executeMutation(
182 testClient,
183 {
184 mutationKey: key,
185 mutationFn: () => Promise.resolve({ data: 5 }),
186 onMutate: () => 'context',
187 },
188 'vars',
189 )
190 } catch {}
191​
192 const mutation = testCache.getAll()[0]
193 expect(onMutate).toHaveBeenCalledWith('vars', mutation)
194 })
195​
196 test('should be awaited', async () => {
197 const key = queryKey()
198 const states: Array<number> = []
199 const onMutate = async () => {
200 states.push(1)
201 await sleep(1)
202 states.push(2)
203 }
204 const testCache = new MutationCache({ onMutate })
205 const testClient = createQueryClient({ mutationCache: testCache })
206​
207 executeMutation(
208 testClient,
209 {
210 mutationKey: key,
211 mutationFn: () => Promise.resolve({ data: 5 }),
212 onMutate: async () => {
213 states.push(3)
214 await sleep(1)
215 states.push(4)
216 },
217 },
218 'vars',
219 )
220 await vi.runAllTimersAsync()
221​
222 expect(states).toEqual([1, 2, 3, 4])
223 })
224 })
225​
226 describe('find', () => {
227 test('should filter correctly', async () => {
228 const testCache = new MutationCache()
229 const testClient = createQueryClient({ mutationCache: testCache })
230 const key = ['mutation', 'vars']
231 await executeMutation(
232 testClient,
233 {
234 mutationKey: key,
235 mutationFn: () => Promise.resolve(),
236 },
237 'vars',
238 )
239 const [mutation] = testCache.getAll()
240 expect(testCache.find({ mutationKey: key })).toEqual(mutation)
241 expect(
242 testCache.find({ mutationKey: ['mutation'], exact: false }),
243 ).toEqual(mutation)
244 expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined)
245 expect(
246 testCache.find({
247 predicate: (m) => m.options.mutationKey?.[0] === key[0],
248 }),
249 ).toEqual(mutation)
250 })
251 })
252​
253 describe('findAll', () => {
254 test('should filter correctly', async () => {
255 const testCache = new MutationCache()
256 const testClient = createQueryClient({ mutationCache: testCache })
257 await executeMutation(
258 testClient,
259 {
260 mutationKey: ['a', 1],
261 mutationFn: () => Promise.resolve(),
262 },
263 1,
264 )
265 await executeMutation(
266 testClient,
267 {
268 mutationKey: ['a', 2],
269 mutationFn: () => Promise.resolve(),
270 },
271 2,
272 )
273 await executeMutation(
274 testClient,
275 {
276 mutationKey: ['b'],
277 mutationFn: () => Promise.resolve(),
278 },
279 3,
280 )
281​
282 const [mutation1, mutation2] = testCache.getAll()
283 expect(
284 testCache.findAll({ mutationKey: ['a'], exact: false }),
285 ).toHaveLength(2)
286 expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1)
287 expect(
288 testCache.findAll({
289 predicate: (m) => m.options.mutationKey?.[1] === 2,
290 }),
291 ).toEqual([mutation2])
292 expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([])
293 })
294 })
295​
296 describe('garbage collection', () => {
297 test('should remove unused mutations after gcTime has elapsed', async () => {
298 const testCache = new MutationCache()
299 const testClient = createQueryClient({ mutationCache: testCache })
300 const onSuccess = vi.fn()
301 executeMutation(
302 testClient,
303 {
304 mutationKey: ['a', 1],
305 gcTime: 10,
306 mutationFn: () => Promise.resolve(),
307 onSuccess,
308 },
309 1,
310 )
311 expect(testCache.getAll()).toHaveLength(1)
312 await vi.waitFor(() => {
313 expect(testCache.getAll()).toHaveLength(0)
314 })
315 expect(onSuccess).toHaveBeenCalledTimes(1)
316 })
317​
318 test('should not remove mutations if there are active observers', async () => {
319 const queryClient = createQueryClient()
320 const observer = new MutationObserver(queryClient, {
321 gcTime: 10,
322 mutationFn: (input: number) => Promise.resolve(input),
323 })
324 const unsubscribe = observer.subscribe(() => undefined)
325​
326 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
327 observer.mutate(1)
328 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
329 await vi.advanceTimersByTimeAsync(10)
330 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
331 unsubscribe()
332 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
333 await vi.advanceTimersByTimeAsync(10)
334 await vi.waitFor(() => {
335 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
336 })
337 })
338​
339 test('should be garbage collected later when unsubscribed and mutation is pending', async () => {
340 const queryClient = createQueryClient()
341 const onSuccess = vi.fn()
342 const observer = new MutationObserver(queryClient, {
343 gcTime: 10,
344 mutationFn: async () => {
345 await sleep(20)
346 return 'data'
347 },
348 onSuccess,
349 })
350 const unsubscribe = observer.subscribe(() => undefined)
351 observer.mutate(1)
352 unsubscribe()
353 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
354 await vi.advanceTimersByTimeAsync(10)
355 // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending
356 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
357 await vi.advanceTimersByTimeAsync(10)
358 // should be removed after an additional gcTime wait
359 await vi.waitFor(() => {
360 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
361 })
362 expect(onSuccess).toHaveBeenCalledTimes(1)
363 })
364​
365 test('should call callbacks even with gcTime 0 and mutation still pending', async () => {
366 const queryClient = createQueryClient()
367 const onSuccess = vi.fn()
368 const observer = new MutationObserver(queryClient, {
369 gcTime: 0,
370 mutationFn: async () => {
371 return 'data'
372 },
373 onSuccess,
374 })
375 const unsubscribe = observer.subscribe(() => undefined)
376 observer.mutate(1)
377 unsubscribe()
378 await vi.waitFor(() => {
379 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
380 })
381 expect(onSuccess).toHaveBeenCalledTimes(1)
382 })
383 })
384})