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

persist.test.ts

359 lines10.6 KB

1import {
2 MutationObserver,
3 QueriesObserver,
4 QueryClient,
5 dehydrate,
6} from '@tanstack/query-core'
7import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
8import {
9 persistQueryClient,
10 persistQueryClientRestore,
11 persistQueryClientSubscribe,
12} from '../persist'
13import { createMockPersister, createSpyPersister } from './utils'
14​
15describe('persist', () => {
16 let queryClient: QueryClient
17​
18 beforeEach(() => {
19 queryClient = new QueryClient()
20 })
21​
22 afterEach(() => {
23 queryClient.clear()
24 })
25​
26 describe('persistQueryClientSubscribe', () => {
27 it('should persist mutations', async () => {
28 const persister = createMockPersister()
29​
30 const unsubscribe = persistQueryClientSubscribe({
31 queryClient,
32 persister,
33 dehydrateOptions: { shouldDehydrateMutation: () => true },
34 })
35​
36 queryClient.getMutationCache().build(queryClient, {
37 mutationFn: (text: string) => Promise.resolve(text),
38 })
39​
40 const result = await persister.restoreClient()
41 expect(result?.clientState.mutations).toHaveLength(1)
42​
43 unsubscribe()
44 })
45​
46 it('should catch and log errors in `persistClient`', async () => {
47 const consoleErrorMock = vi
48 .spyOn(console, 'error')
49 .mockReturnValue(undefined)
50 const consoleWarnMock = vi
51 .spyOn(console, 'warn')
52 .mockReturnValue(undefined)
53​
54 const persistError = new Error('Error persisting client')
55 const persister = createSpyPersister()
56 vi.spyOn(persister, 'persistClient').mockRejectedValue(persistError)
57​
58 const unsubscribe = persistQueryClientSubscribe({
59 queryClient,
60 persister,
61 })
62​
63 // Triggers 2 saves: the query being added and its data being updated
64 queryClient.setQueryData(['key'], 'data')
65 await vi.waitFor(() => expect(consoleErrorMock).toHaveBeenCalledTimes(2))
66​
67 expect(persister.persistClient).toHaveBeenCalledTimes(2)
68 expect(consoleErrorMock).toHaveBeenNthCalledWith(1, persistError)
69 expect(consoleErrorMock).toHaveBeenNthCalledWith(2, persistError)
70 expect(consoleWarnMock).toHaveBeenCalledTimes(2)
71​
72 unsubscribe()
73 consoleErrorMock.mockRestore()
74 consoleWarnMock.mockRestore()
75 })
76​
77 it('should catch and log errors thrown while dehydrating', async () => {
78 const consoleErrorMock = vi
79 .spyOn(console, 'error')
80 .mockReturnValue(undefined)
81 const consoleWarnMock = vi
82 .spyOn(console, 'warn')
83 .mockReturnValue(undefined)
84​
85 const dehydrateError = new Error('Error dehydrating query')
86 const persister = createSpyPersister()
87​
88 const unsubscribe = persistQueryClientSubscribe({
89 queryClient,
90 persister,
91 dehydrateOptions: {
92 shouldDehydrateQuery: () => {
93 throw dehydrateError
94 },
95 },
96 })
97​
98 // Triggers 2 saves: the query being added and its data being updated
99 queryClient.setQueryData(['key'], 'data')
100 await vi.waitFor(() => expect(consoleErrorMock).toHaveBeenCalledTimes(2))
101​
102 expect(persister.persistClient).not.toHaveBeenCalled()
103 expect(consoleErrorMock).toHaveBeenNthCalledWith(1, dehydrateError)
104 expect(consoleErrorMock).toHaveBeenNthCalledWith(2, dehydrateError)
105 expect(consoleWarnMock).toHaveBeenCalledTimes(2)
106​
107 unsubscribe()
108 consoleErrorMock.mockRestore()
109 consoleWarnMock.mockRestore()
110 })
111 })
112​
113 describe('persistQueryClientSave', () => {
114 it('should not be triggered on observer type events', () => {
115 const persister = createSpyPersister()
116​
117 const unsubscribe = persistQueryClientSubscribe({
118 queryClient,
119 persister,
120 })
121​
122 const queryKey = ['test']
123 const queryFn = vi.fn<() => number>().mockReturnValue(1)
124 const observer = new QueriesObserver(queryClient, [{ queryKey, queryFn }])
125 const unsubscribeObserver = observer.subscribe(vi.fn())
126 observer
127 .getObservers()[0]
128 ?.setOptions({ queryKey, refetchOnWindowFocus: false })
129 unsubscribeObserver()
130​
131 queryClient.setQueryData(queryKey, 2)
132​
133 // persistClient should be called 3 times:
134 // 1. When query is added
135 // 2. When queryFn is resolved
136 // 3. When setQueryData is called
137 // All events fired by manipulating observers are ignored
138 expect(persister.persistClient).toHaveBeenCalledTimes(3)
139​
140 unsubscribe()
141 })
142​
143 it('should not be triggered on mutation observer type events', () => {
144 const persister = createSpyPersister()
145​
146 const unsubscribe = persistQueryClientSubscribe({
147 queryClient,
148 persister,
149 })
150​
151 const observer = new MutationObserver(queryClient, {
152 mutationFn: () => Promise.resolve('data'),
153 })
154 const unsubscribeObserver = observer.subscribe(vi.fn())
155 observer.setOptions({ mutationKey: ['test'] })
156 unsubscribeObserver()
157​
158 // Events fired by manipulating the mutation observer are not cache
159 // events, so they must not trigger a persist.
160 expect(persister.persistClient).not.toHaveBeenCalled()
161​
162 unsubscribe()
163 })
164 })
165​
166 describe('persistQueryClientRestore', () => {
167 let persister: ReturnType<typeof createSpyPersister>
168​
169 beforeEach(() => {
170 persister = createSpyPersister()
171 })
172​
173 it('should rethrow exceptions in `restoreClient`', async () => {
174 const consoleErrorMock = vi
175 .spyOn(console, 'error')
176 .mockReturnValue(undefined)
177​
178 const consoleWarnMock = vi
179 .spyOn(console, 'warn')
180 .mockReturnValue(undefined)
181​
182 const restoreError = new Error('Error restoring client')
183​
184 persister.restoreClient = () => Promise.reject(restoreError)
185​
186 await expect(
187 persistQueryClientRestore({
188 queryClient,
189 persister,
190 }),
191 ).rejects.toBe(restoreError)
192​
193 expect(consoleErrorMock).toHaveBeenCalledTimes(1)
194 expect(consoleWarnMock).toHaveBeenCalledTimes(1)
195 expect(consoleErrorMock).toHaveBeenNthCalledWith(1, restoreError)
196 })
197​
198 it('should rethrow exceptions in `removeClient` before `restoreClient`', async () => {
199 const consoleErrorMock = vi
200 .spyOn(console, 'error')
201 .mockReturnValue(undefined)
202​
203 const consoleWarnMock = vi
204 .spyOn(console, 'warn')
205 .mockReturnValue(undefined)
206​
207 const restoreError = new Error('Error restoring client')
208 const removeError = new Error('Error removing client')
209​
210 persister.restoreClient = () => Promise.reject(restoreError)
211 persister.removeClient = () => Promise.reject(removeError)
212​
213 await expect(
214 persistQueryClientRestore({
215 queryClient,
216 persister,
217 }),
218 ).rejects.toBe(removeError)
219​
220 expect(consoleErrorMock).toHaveBeenCalledTimes(1)
221 expect(consoleWarnMock).toHaveBeenCalledTimes(1)
222 expect(consoleErrorMock).toHaveBeenNthCalledWith(1, restoreError)
223 })
224​
225 it('should rethrow error in `removeClient`', async () => {
226 const removeError = new Error('Error removing client')
227​
228 persister.removeClient = () => Promise.reject(removeError)
229 persister.restoreClient = () => {
230 return Promise.resolve({
231 buster: 'random-buster',
232 clientState: {
233 mutations: [],
234 queries: [],
235 },
236 timestamp: new Date().getTime(),
237 })
238 }
239​
240 await expect(
241 persistQueryClientRestore({
242 queryClient,
243 persister,
244 }),
245 ).rejects.toBe(removeError)
246 })
247​
248 it('should hydrate the query client when the persisted cache is valid', async () => {
249 const sourceClient = new QueryClient()
250 sourceClient.setQueryData(['key'], 'data')
251​
252 persister.restoreClient = () =>
253 Promise.resolve({
254 buster: '',
255 clientState: dehydrate(sourceClient),
256 timestamp: Date.now(),
257 })
258​
259 await persistQueryClientRestore({
260 queryClient,
261 persister,
262 })
263 expect(persister.removeClient).not.toHaveBeenCalled()
264 expect(queryClient.getQueryData(['key'])).toBe('data')
265 })
266​
267 it('should remove the client when the persisted cache is expired', async () => {
268 persister.restoreClient = () =>
269 Promise.resolve({
270 buster: '',
271 clientState: { mutations: [], queries: [] },
272 timestamp: Date.now() - 1000,
273 })
274​
275 await persistQueryClientRestore({
276 queryClient,
277 persister,
278 maxAge: 100,
279 })
280 expect(persister.removeClient).toHaveBeenCalledTimes(1)
281 })
282​
283 it('should remove the client when the buster does not match', async () => {
284 persister.restoreClient = () =>
285 Promise.resolve({
286 buster: 'old-buster',
287 clientState: { mutations: [], queries: [] },
288 timestamp: Date.now(),
289 })
290​
291 await persistQueryClientRestore({
292 queryClient,
293 persister,
294 buster: 'new-buster',
295 })
296 expect(persister.removeClient).toHaveBeenCalledTimes(1)
297 })
298​
299 it('should remove the client when the persisted cache has no timestamp', async () => {
300 persister.restoreClient = () =>
301 Promise.resolve({
302 buster: '',
303 clientState: { mutations: [], queries: [] },
304 timestamp: 0,
305 })
306​
307 await persistQueryClientRestore({
308 queryClient,
309 persister,
310 })
311 expect(persister.removeClient).toHaveBeenCalledTimes(1)
312 })
313 })
314​
315 describe('persistQueryClient', () => {
316 it('should subscribe to the query cache after a successful restore', async () => {
317 const persister = createSpyPersister()
318 persister.restoreClient = () => Promise.resolve(undefined)
319​
320 const [unsubscribe, restorePromise] = persistQueryClient({
321 queryClient,
322 persister,
323 })
324 await restorePromise
325​
326 queryClient.setQueryData(['key'], 'data')
327 expect(persister.persistClient).toHaveBeenCalledWith(
328 expect.objectContaining({
329 clientState: expect.objectContaining({
330 queries: [expect.objectContaining({ queryKey: ['key'] })],
331 }),
332 }),
333 )
334​
335 unsubscribe()
336 })
337​
338 it('should not subscribe when unsubscribed before the restore completes', async () => {
339 const persister = createSpyPersister()
340 let resolveRestore: () => void
341 persister.restoreClient = () =>
342 new Promise((resolve) => {
343 resolveRestore = () => resolve(undefined)
344 })
345​
346 const [unsubscribe, restorePromise] = persistQueryClient({
347 queryClient,
348 persister,
349 })
350 // Unsubscribe before the restore resolves
351 unsubscribe()
352 resolveRestore!()
353 await restorePromise
354​
355 queryClient.setQueryData(['key'], 'data')
356 expect(persister.persistClient).not.toHaveBeenCalled()
357 })
358 })
359})