-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
use-swr-cache.test.tsx
498 lines (434 loc) · 12.8 KB
/
use-swr-cache.test.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import { act, fireEvent, screen } from '@testing-library/react'
import React, { useState, StrictMode } from 'react'
import useSWR, { useSWRConfig, SWRConfig, mutate as globalMutate } from 'swr'
import {
sleep,
createKey,
createResponse,
nextTick,
focusOn,
renderWithConfig,
renderWithGlobalCache
} from './utils'
describe('useSWR - cache provider', () => {
let provider
beforeEach(() => {
provider = new Map()
})
it('should be able to update the cache', async () => {
const fetcher = _key => 'res:' + _key
const keys = [createKey(), createKey()]
function Page() {
const [index, setIndex] = useState(0)
const { data } = useSWR(keys[index], fetcher)
return <div onClick={() => setIndex(1)}>{data}</div>
}
renderWithConfig(<Page />, { provider: () => provider })
await screen.findByText(fetcher(keys[0]))
expect(provider.get(keys[1])?.data).toBe(undefined)
fireEvent.click(screen.getByText(fetcher(keys[0])))
await act(() => sleep(10))
expect(provider.get(keys[0])?.data).toBe(fetcher(keys[0]))
expect(provider.get(keys[1])?.data).toBe(fetcher(keys[1]))
})
it('should be able to read from the initial cache with updates', async () => {
const key = createKey()
const renderedValues = []
const fetcher = () => createResponse('updated value', { delay: 10 })
function Page() {
const { data } = useSWR(key, fetcher)
renderedValues.push(data)
return <div>{data}</div>
}
renderWithConfig(<Page />, {
provider: () => new Map([[key, { data: 'cached value' }]])
})
screen.getByText('cached value')
await screen.findByText('updated value')
expect(renderedValues.length).toBe(2)
})
it('should correctly mutate the cached value', async () => {
const key = createKey()
let mutate
function Page() {
const { mutate: mutateWithCache } = useSWRConfig()
mutate = mutateWithCache
const { data } = useSWR(key, null)
return <div>{data}</div>
}
renderWithConfig(<Page />, {
provider: () => new Map([[key, { data: 'cached value' }]])
})
screen.getByText('cached value')
await act(() => mutate(key, 'mutated value', false))
await screen.findByText('mutated value')
})
it('should support multi-level cache', async () => {
const key = createKey()
// Nested components with the same cache key can get different values.
function Foo() {
const { data } = useSWR(key, null)
return <>{data}</>
}
function Page() {
const { data } = useSWR(key, null)
return (
<div>
{data}:
<SWRConfig
value={{ provider: () => new Map([[key, { data: '2' }]]) }}
>
<Foo />
</SWRConfig>
</div>
)
}
renderWithConfig(<Page />, {
provider: () => new Map([[key, { data: '1' }]])
})
screen.getByText('1:2')
})
it('should support isolated cache', async () => {
const key = createKey()
// Nested components with the same cache key can get different values.
function Foo() {
const { data } = useSWR(key, null)
return <>{data}</>
}
function Page() {
return (
<div>
<SWRConfig
value={{ provider: () => new Map([[key, { data: '1' }]]) }}
>
<Foo />
</SWRConfig>
:
<SWRConfig
value={{ provider: () => new Map([[key, { data: '2' }]]) }}
>
<Foo />
</SWRConfig>
</div>
)
}
renderWithConfig(<Page />)
screen.getByText('1:2')
})
it('should respect provider options', async () => {
const key = createKey()
const focusFn = jest.fn()
const unsubscribeFocusFn = jest.fn()
const unsubscribeReconnectFn = jest.fn()
let value = 1
function Page() {
const { data } = useSWR(key, () => value++, {
dedupingInterval: 0
})
return <>{String(data)}</>
}
const { unmount } = renderWithConfig(<Page />, {
provider: () => new Map([[key, { data: 0 }]]),
initFocus() {
focusFn()
return unsubscribeFocusFn
},
initReconnect() {
/* do nothing */
return unsubscribeReconnectFn
}
})
screen.getByText('0')
// mount
await screen.findByText('1')
await nextTick()
// try to trigger revalidation, but shouldn't work
await focusOn(window)
// revalidateOnFocus won't work
screen.getByText('1')
unmount()
expect(focusFn).toBeCalled()
expect(unsubscribeFocusFn).toBeCalledTimes(1)
expect(unsubscribeReconnectFn).toBeCalledTimes(1)
})
it('should work with revalidateOnFocus', async () => {
const key = createKey()
let value = 0
function Page() {
const { data } = useSWR(key, () => value++, {
dedupingInterval: 0
})
return <>{String(data)}</>
}
renderWithConfig(<Page />, { provider: () => provider })
screen.getByText('undefined')
await screen.findByText('0')
await nextTick()
await focusOn(window)
await nextTick()
screen.getByText('1')
})
it('should support fallback values with custom provider', async () => {
const key = createKey()
function Page() {
const { data, isFallback } = useSWR(key, async () => {
await sleep(10)
return 'data'
})
return (
<>
{String(data)},{String(isFallback)}
</>
)
}
renderWithConfig(<Page />, {
provider: () => provider,
fallback: { [key]: 'fallback' }
})
screen.getByText('fallback,true') // no `undefined`, directly fallback
await screen.findByText('data,false')
})
it('should not return the fallback if cached', async () => {
const key = createKey()
function Page() {
const { data } = useSWR(key, async () => {
await sleep(10)
return 'data'
})
return <>{String(data)}</>
}
renderWithConfig(<Page />, {
provider: () => new Map([[key, { data: 'cache' }]]),
fallback: { [key]: 'fallback' }
})
screen.getByText('cache') // no `undefined`, directly from cache
await screen.findByText('data')
})
it.skip('should be able to extend the parent cache', async () => {
let parentCache
const key = createKey()
function Page() {
const { data } = useSWR(key, async () => {
await sleep(10)
return 'data'
})
return <>{String(data)}</>
}
renderWithConfig(<Page />, {
provider: parentCache_ => {
parentCache = parentCache_
return {
set: (k, v) => parentCache_.set(k, v),
get: k => {
// We append `-extended` to the value returned by the parent cache.
const v = parentCache_.get(k)
if (v && typeof v.data !== 'undefined') {
return { ...v, data: v.data + '-extended' }
}
return v
},
delete: k => parentCache_.delete(k)
}
}
})
expect(parentCache).toBe(SWRConfig.default.cache)
screen.getByText('undefined')
await screen.findByText('data-extended')
})
it('should return the cache instance from the useSWRConfig', async () => {
let cache
function Page() {
cache = useSWRConfig().cache
return null
}
renderWithConfig(<Page />, { provider: () => provider })
expect(provider).toBe(cache)
})
it('should retain the correct cache hierarchy', async () => {
const key = createKey()
const fetcher = async () => {
await sleep(10)
return 'data'
}
function Foo() {
const { data } = useSWR(key, fetcher)
return <>{String(data)}</>
}
function Bar() {
const { data } = useSWR(key, fetcher)
return <>{String(data)}</>
}
function Page() {
const { data } = useSWR(key, fetcher)
return (
<div>
{String(data)},
<SWRConfig value={{ fallback: { [key]: 'fallback' } }}>
<Foo />
</SWRConfig>
,
<Bar />
</div>
)
}
renderWithConfig(<Page />)
screen.getByText('undefined,fallback,undefined')
await screen.findByText('data,data,data')
})
it('should not recreate the cache if rerendering', async () => {
const createCacheProvider = jest.fn()
let rerender
function Page() {
rerender = useState({})[1]
return (
<SWRConfig
value={{
provider: () => {
createCacheProvider()
return provider
}
}}
/>
)
}
renderWithConfig(<Page />)
expect(createCacheProvider).toBeCalledTimes(1)
act(() => rerender({}))
expect(createCacheProvider).toBeCalledTimes(1)
})
})
describe('useSWR - global cache', () => {
it('should return the global cache and mutate by default', async () => {
let localCache, localMutate
function Page() {
const { cache, mutate } = useSWRConfig()
localCache = cache
localMutate = mutate
return null
}
renderWithGlobalCache(<Page />)
expect(localCache).toBe(SWRConfig.default.cache)
expect(localMutate).toBe(globalMutate)
})
it('should be able to update the cache', async () => {
const fetcher = _key => 'res:' + _key
const keys = [createKey(), createKey()]
let cache
function Page() {
const [index, setIndex] = useState(0)
cache = useSWRConfig().cache
const { data } = useSWR(keys[index], fetcher)
return <div onClick={() => setIndex(1)}>{data}</div>
}
renderWithGlobalCache(<Page />)
await screen.findByText(fetcher(keys[0]))
expect(cache.get(keys[1])?.data).toBe(undefined)
fireEvent.click(screen.getByText(fetcher(keys[0])))
await act(() => sleep(10))
expect(cache.get(keys[0])?.data).toBe(fetcher(keys[0]))
expect(cache.get(keys[1])?.data).toBe(fetcher(keys[1]))
})
it('should correctly mutate the cached value', async () => {
const key = createKey()
let mutate
function Page() {
const { mutate: mutateWithCache } = useSWRConfig()
mutate = mutateWithCache
const { data } = useSWR(key, null)
return <div>data:{data}</div>
}
renderWithGlobalCache(<Page />)
screen.getByText('data:')
await act(() => mutate(key, 'mutated value', false))
await screen.findByText('data:mutated value')
})
it('should work with revalidateOnFocus', async () => {
const key = createKey()
let value = 0
function Page() {
const { data } = useSWR(key, () => value++, {
dedupingInterval: 0
})
return <>{String(data)}</>
}
renderWithGlobalCache(<Page />)
screen.getByText('undefined')
await screen.findByText('0')
await nextTick()
await focusOn(window)
await nextTick()
screen.getByText('1')
})
it('should support fallback values', async () => {
const key = createKey()
function Page() {
const { data } = useSWR(key, async () => {
await sleep(10)
return 'data'
})
return <>{String(data)}</>
}
renderWithGlobalCache(<Page />, { fallback: { [key]: 'fallback' } })
screen.getByText('fallback') // no `undefined`, directly fallback
await screen.findByText('data')
})
it('should reusing the same cache instance after unmounting SWRConfig', async () => {
let focusEventRegistered = false
const cacheSingleton = new Map([['key', { data: 'value' }]])
function Page() {
return (
<SWRConfig
value={{
provider: () => cacheSingleton,
initFocus: () => {
focusEventRegistered = true
return () => (focusEventRegistered = false)
}
}}
>
<Comp />
</SWRConfig>
)
}
function Comp() {
const { cache } = useSWRConfig()
return <>{String(cache.get('key')?.data)}</>
}
function Wrapper() {
const [mount, setMountPage] = useState(true)
return (
<>
<button onClick={() => setMountPage(!mount)}>toggle</button>
{mount ? <Page /> : null}
</>
)
}
renderWithGlobalCache(<Wrapper />)
await screen.findByText('value')
fireEvent.click(screen.getByText('toggle'))
fireEvent.click(screen.getByText('toggle'))
await screen.findByText('value')
expect(focusEventRegistered).toEqual(true)
})
it('should correctly return the cache instance under strict mode', async () => {
function Page() {
// Intentionally do this.
const [cache] = useState(new Map([['key', { data: 'value' }]]))
return (
<SWRConfig value={{ provider: () => cache }}>
<Comp />
</SWRConfig>
)
}
function Comp() {
const { cache } = useSWRConfig()
return <>{String(cache.get('key')?.data)}</>
}
renderWithGlobalCache(
<StrictMode>
<Page />
</StrictMode>
)
await screen.findByText('value')
})
})