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

mutationCache.test.tsx

260 lines8.5 KB

1import { waitFor } from '@testing-library/react'
2import {
3 queryKey,
4 sleep,
5 executeMutation,
6 createQueryClient,
7} from '../../../../tests/utils'
8import { MutationCache, MutationObserver } from '..'
9​
10describe('mutationCache', () => {
11 describe('MutationCacheConfig.onError', () => {
12 test('should be called when a mutation errors', async () => {
13 const key = queryKey()
14 const onError = jest.fn()
15 const testCache = new MutationCache({ onError })
16 const testClient = createQueryClient({ mutationCache: testCache })
17​
18 try {
19 await executeMutation(testClient, {
20 mutationKey: key,
21 variables: 'vars',
22 mutationFn: () => Promise.reject('error'),
23 onMutate: () => 'context',
24 })
25 } catch {}
26​
27 const mutation = testCache.getAll()[0]
28 expect(onError).toHaveBeenCalledWith('error', 'vars', 'context', mutation)
29 })
30 })
31 describe('MutationCacheConfig.onSuccess', () => {
32 test('should be called when a mutation is successful', async () => {
33 const key = queryKey()
34 const onSuccess = jest.fn()
35 const testCache = new MutationCache({ onSuccess })
36 const testClient = createQueryClient({ mutationCache: testCache })
37​
38 try {
39 await executeMutation(testClient, {
40 mutationKey: key,
41 variables: 'vars',
42 mutationFn: () => Promise.resolve({ data: 5 }),
43 onMutate: () => 'context',
44 })
45 } catch {}
46​
47 const mutation = testCache.getAll()[0]
48 expect(onSuccess).toHaveBeenCalledWith(
49 { data: 5 },
50 'vars',
51 'context',
52 mutation,
53 )
54 })
55 })
56 describe('MutationCacheConfig.onMutate', () => {
57 test('should be called before a mutation executes', async () => {
58 const key = queryKey()
59 const onMutate = jest.fn()
60 const testCache = new MutationCache({ onMutate })
61 const testClient = createQueryClient({ mutationCache: testCache })
62​
63 try {
64 await executeMutation(testClient, {
65 mutationKey: key,
66 variables: 'vars',
67 mutationFn: () => Promise.resolve({ data: 5 }),
68 onMutate: () => 'context',
69 })
70 } catch {}
71​
72 const mutation = testCache.getAll()[0]
73 expect(onMutate).toHaveBeenCalledWith('vars', mutation)
74 })
75 })
76​
77 describe('find', () => {
78 test('should filter correctly', async () => {
79 const testCache = new MutationCache()
80 const testClient = createQueryClient({ mutationCache: testCache })
81 const key = ['mutation', 'vars']
82 await executeMutation(testClient, {
83 mutationKey: key,
84 variables: 'vars',
85 mutationFn: () => Promise.resolve(),
86 })
87 const [mutation] = testCache.getAll()
88 expect(testCache.find({ mutationKey: key })).toEqual(mutation)
89 expect(
90 testCache.find({ mutationKey: ['mutation'], exact: false }),
91 ).toEqual(mutation)
92 expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined)
93 expect(
94 testCache.find({ predicate: (m) => m.options.variables === 'vars' }),
95 ).toEqual(mutation)
96 })
97 })
98​
99 describe('findAll', () => {
100 test('should filter correctly', async () => {
101 const testCache = new MutationCache()
102 const testClient = createQueryClient({ mutationCache: testCache })
103 await executeMutation(testClient, {
104 mutationKey: ['a', 1],
105 variables: 1,
106 mutationFn: () => Promise.resolve(),
107 })
108 await executeMutation(testClient, {
109 mutationKey: ['a', 2],
110 variables: 2,
111 mutationFn: () => Promise.resolve(),
112 })
113 await executeMutation(testClient, {
114 mutationKey: ['b'],
115 mutationFn: () => Promise.resolve(),
116 })
117​
118 const [mutation1, mutation2] = testCache.getAll()
119 expect(
120 testCache.findAll({ mutationKey: ['a'], exact: false }),
121 ).toHaveLength(2)
122 expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1)
123 expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([])
124 expect(
125 testCache.findAll({ predicate: (m) => m.options.variables === 2 }),
126 ).toEqual([mutation2])
127 })
128 })
129​
130 describe('garbage collection', () => {
131 test('should remove unused mutations after cacheTime has elapsed', async () => {
132 const testCache = new MutationCache()
133 const testClient = createQueryClient({ mutationCache: testCache })
134 const onSuccess = jest.fn()
135 await executeMutation(testClient, {
136 mutationKey: ['a', 1],
137 variables: 1,
138 cacheTime: 10,
139 mutationFn: () => Promise.resolve(),
140 onSuccess,
141 })
142​
143 expect(testCache.getAll()).toHaveLength(1)
144 await sleep(10)
145 await waitFor(() => {
146 expect(testCache.getAll()).toHaveLength(0)
147 })
148 expect(onSuccess).toHaveBeenCalledTimes(1)
149 })
150​
151 test('should not remove mutations if there are active observers', async () => {
152 const queryClient = createQueryClient()
153 const observer = new MutationObserver(queryClient, {
154 variables: 1,
155 cacheTime: 10,
156 mutationFn: () => Promise.resolve(),
157 })
158 const unsubscribe = observer.subscribe(() => undefined)
159​
160 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
161 observer.mutate(1)
162 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
163 await sleep(10)
164 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
165 unsubscribe()
166 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
167 await sleep(10)
168 await waitFor(() => {
169 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
170 })
171 })
172​
173 test('should only remove when the last observer unsubscribes', async () => {
174 const queryClient = createQueryClient()
175 const observer1 = new MutationObserver(queryClient, {
176 variables: 1,
177 cacheTime: 10,
178 mutationFn: async () => {
179 await sleep(10)
180 return 'update1'
181 },
182 })
183​
184 const observer2 = new MutationObserver(queryClient, {
185 cacheTime: 10,
186 mutationFn: async () => {
187 await sleep(10)
188 return 'update2'
189 },
190 })
191​
192 await observer1.mutate()
193​
194 // we currently have no way to add multiple observers to the same mutation
195 const currentMutation = observer1['currentMutation']!
196 currentMutation.addObserver(observer1)
197 currentMutation.addObserver(observer2)
198​
199 expect(currentMutation['observers'].length).toEqual(2)
200 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
201​
202 currentMutation.removeObserver(observer1)
203 currentMutation.removeObserver(observer2)
204 expect(currentMutation['observers'].length).toEqual(0)
205 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
206 // wait for cacheTime to gc
207 await sleep(10)
208 await waitFor(() => {
209 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
210 })
211 })
212​
213 test('should be garbage collected later when unsubscribed and mutation is loading', async () => {
214 const queryClient = createQueryClient()
215 const onSuccess = jest.fn()
216 const observer = new MutationObserver(queryClient, {
217 variables: 1,
218 cacheTime: 10,
219 mutationFn: async () => {
220 await sleep(20)
221 return 'data'
222 },
223 onSuccess,
224 })
225 const unsubscribe = observer.subscribe(() => undefined)
226 observer.mutate(1)
227 unsubscribe()
228 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
229 await sleep(10)
230 // unsubscribe should not remove even though cacheTime has elapsed b/c mutation is still loading
231 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
232 await sleep(10)
233 // should be removed after an additional cacheTime wait
234 await waitFor(() => {
235 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
236 })
237 expect(onSuccess).toHaveBeenCalledTimes(1)
238 })
239​
240 test('should call callbacks even with cacheTime 0 and mutation still loading', async () => {
241 const queryClient = createQueryClient()
242 const onSuccess = jest.fn()
243 const observer = new MutationObserver(queryClient, {
244 variables: 1,
245 cacheTime: 0,
246 mutationFn: async () => {
247 return 'data'
248 },
249 onSuccess,
250 })
251 const unsubscribe = observer.subscribe(() => undefined)
252 observer.mutate(1)
253 unsubscribe()
254 await waitFor(() => {
255 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
256 })
257 expect(onSuccess).toHaveBeenCalledTimes(1)
258 })
259 })
260})