forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueryObserver.test.tsx
802 lines (708 loc) · 22.1 KB
/
queryObserver.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
import {
sleep,
queryKey,
expectType,
mockLogger,
createQueryClient,
} from '../../../../tests/utils'
import {
QueryClient,
QueryObserver,
QueryObserverResult,
focusManager,
} from '..'
describe('queryObserver', () => {
let queryClient: QueryClient
beforeEach(() => {
queryClient = createQueryClient()
queryClient.mount()
})
afterEach(() => {
queryClient.clear()
})
test('should trigger a fetch when subscribed', async () => {
const key = queryKey()
const queryFn = jest.fn<string, unknown[]>().mockReturnValue('data')
const observer = new QueryObserver(queryClient, { queryKey: key, queryFn })
const unsubscribe = observer.subscribe(() => undefined)
await sleep(1)
unsubscribe()
expect(queryFn).toHaveBeenCalledTimes(1)
})
test('should notify when switching query', async () => {
const key1 = queryKey()
const key2 = queryKey()
const results: QueryObserverResult[] = []
const observer = new QueryObserver(queryClient, {
queryKey: key1,
queryFn: () => 1,
})
const unsubscribe = observer.subscribe((result) => {
results.push(result)
})
await sleep(1)
observer.setOptions({ queryKey: key2, queryFn: () => 2 })
await sleep(1)
unsubscribe()
expect(results.length).toBe(4)
expect(results[0]).toMatchObject({ data: undefined, status: 'loading' })
expect(results[1]).toMatchObject({ data: 1, status: 'success' })
expect(results[2]).toMatchObject({ data: undefined, status: 'loading' })
expect(results[3]).toMatchObject({ data: 2, status: 'success' })
})
test('should be able to fetch with a selector', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => ({ count: 1 }),
select: (data) => ({ myCount: data.count }),
})
let observerResult
const unsubscribe = observer.subscribe((result) => {
expectType<QueryObserverResult<{ myCount: number }>>(result)
observerResult = result
})
await sleep(1)
unsubscribe()
expect(observerResult).toMatchObject({ data: { myCount: 1 } })
})
test('should be able to fetch with a selector using the fetch method', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => ({ count: 1 }),
select: (data) => ({ myCount: data.count }),
})
const observerResult = await observer.refetch()
expectType<{ myCount: number } | undefined>(observerResult.data)
expect(observerResult.data).toMatchObject({ myCount: 1 })
})
test('should be able to fetch with a selector and object syntax', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => ({ count: 1 }),
select: (data) => ({ myCount: data.count }),
})
let observerResult
const unsubscribe = observer.subscribe((result) => {
observerResult = result
})
await sleep(1)
unsubscribe()
expect(observerResult).toMatchObject({ data: { myCount: 1 } })
})
test('should run the selector again if the data changed', async () => {
const key = queryKey()
let count = 0
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => ({ count }),
select: (data) => {
count++
return { myCount: data.count }
},
})
const observerResult1 = await observer.refetch()
const observerResult2 = await observer.refetch()
expect(count).toBe(2)
expect(observerResult1.data).toMatchObject({ myCount: 0 })
expect(observerResult2.data).toMatchObject({ myCount: 1 })
})
test('should run the selector again if the selector changed', async () => {
const key = queryKey()
let count = 0
const results: QueryObserverResult[] = []
const queryFn = () => ({ count: 1 })
const select1 = (data: ReturnType<typeof queryFn>) => {
count++
return { myCount: data.count }
}
const select2 = (_data: ReturnType<typeof queryFn>) => {
count++
return { myCount: 99 }
}
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
select: select1,
})
const unsubscribe = observer.subscribe((result) => {
results.push(result)
})
await sleep(1)
observer.setOptions({
queryKey: key,
queryFn,
select: select2,
})
await sleep(1)
await observer.refetch()
unsubscribe()
expect(count).toBe(2)
expect(results.length).toBe(5)
expect(results[0]).toMatchObject({
status: 'loading',
isFetching: true,
data: undefined,
})
expect(results[1]).toMatchObject({
status: 'success',
isFetching: false,
data: { myCount: 1 },
})
expect(results[2]).toMatchObject({
status: 'success',
isFetching: false,
data: { myCount: 99 },
})
expect(results[3]).toMatchObject({
status: 'success',
isFetching: true,
data: { myCount: 99 },
})
expect(results[4]).toMatchObject({
status: 'success',
isFetching: false,
data: { myCount: 99 },
})
})
test('should not run the selector again if the data and selector did not change', async () => {
const key = queryKey()
let count = 0
const results: QueryObserverResult[] = []
const queryFn = () => ({ count: 1 })
const select = (data: ReturnType<typeof queryFn>) => {
count++
return { myCount: data.count }
}
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
select,
})
const unsubscribe = observer.subscribe((result) => {
results.push(result)
})
await sleep(1)
observer.setOptions({
queryKey: key,
queryFn,
select,
})
await sleep(1)
await observer.refetch()
unsubscribe()
expect(count).toBe(1)
expect(results.length).toBe(4)
expect(results[0]).toMatchObject({
status: 'loading',
isFetching: true,
data: undefined,
})
expect(results[1]).toMatchObject({
status: 'success',
isFetching: false,
data: { myCount: 1 },
})
expect(results[2]).toMatchObject({
status: 'success',
isFetching: true,
data: { myCount: 1 },
})
expect(results[3]).toMatchObject({
status: 'success',
isFetching: false,
data: { myCount: 1 },
})
})
test('should not run the selector again if the data did not change', async () => {
const key = queryKey()
let count = 0
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => ({ count: 1 }),
select: (data) => {
count++
return { myCount: data.count }
},
})
const observerResult1 = await observer.refetch()
const observerResult2 = await observer.refetch()
expect(count).toBe(1)
expect(observerResult1.data).toMatchObject({ myCount: 1 })
expect(observerResult2.data).toMatchObject({ myCount: 1 })
})
test('should always run the selector again if selector throws an error and selector is not referentially stable', async () => {
const key = queryKey()
const results: QueryObserverResult[] = []
const queryFn = async () => {
await sleep(10)
return { count: 1 }
}
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
select: () => {
throw new Error('selector error')
},
})
const unsubscribe = observer.subscribe((result) => {
results.push(result)
})
await sleep(50)
await observer.refetch()
unsubscribe()
expect(results[0]).toMatchObject({
status: 'loading',
isFetching: true,
data: undefined,
})
expect(results[1]).toMatchObject({
status: 'error',
isFetching: false,
data: undefined,
})
expect(results[2]).toMatchObject({
status: 'error',
isFetching: true,
data: undefined,
})
expect(results[3]).toMatchObject({
status: 'error',
isFetching: false,
data: undefined,
})
})
test('should return stale data if selector throws an error', async () => {
const key = queryKey()
const results: QueryObserverResult[] = []
let shouldError = false
const error = new Error('select error')
const observer = new QueryObserver(queryClient, {
queryKey: key,
retry: 0,
queryFn: async () => {
await sleep(10)
return shouldError ? 2 : 1
},
select: (num) => {
if (shouldError) {
throw error
}
shouldError = true
return String(num)
},
})
const unsubscribe = observer.subscribe((result) => {
results.push(result)
})
await sleep(50)
await observer.refetch()
unsubscribe()
expect(results[0]).toMatchObject({
status: 'loading',
isFetching: true,
data: undefined,
error: null,
})
expect(results[1]).toMatchObject({
status: 'success',
isFetching: false,
data: '1',
error: null,
})
expect(results[2]).toMatchObject({
status: 'success',
isFetching: true,
data: '1',
error: null,
})
expect(results[3]).toMatchObject({
status: 'error',
isFetching: false,
data: '1',
error,
})
})
test('should structurally share the selector', async () => {
const key = queryKey()
let count = 0
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => ({ count: ++count }),
select: () => ({ myCount: 1 }),
})
const observerResult1 = await observer.refetch()
const observerResult2 = await observer.refetch()
expect(count).toBe(2)
expect(observerResult1.data).toBe(observerResult2.data)
})
test('should not trigger a fetch when subscribed and disabled', async () => {
const key = queryKey()
const queryFn = jest.fn<string, unknown[]>().mockReturnValue('data')
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
enabled: false,
})
const unsubscribe = observer.subscribe(() => undefined)
await sleep(1)
unsubscribe()
expect(queryFn).toHaveBeenCalledTimes(0)
})
test('should not trigger a fetch when not subscribed', async () => {
const key = queryKey()
const queryFn = jest.fn<string, unknown[]>().mockReturnValue('data')
new QueryObserver(queryClient, { queryKey: key, queryFn })
await sleep(1)
expect(queryFn).toHaveBeenCalledTimes(0)
})
test('should be able to watch a query without defining a query function', async () => {
const key = queryKey()
const queryFn = jest.fn<string, unknown[]>().mockReturnValue('data')
const callback = jest.fn()
const observer = new QueryObserver(queryClient, {
queryKey: key,
enabled: false,
})
const unsubscribe = observer.subscribe(callback)
await queryClient.fetchQuery(key, queryFn)
unsubscribe()
expect(queryFn).toHaveBeenCalledTimes(1)
expect(callback).toHaveBeenCalledTimes(2)
})
test('should accept unresolved query config in update function', async () => {
const key = queryKey()
const queryFn = jest.fn<string, unknown[]>().mockReturnValue('data')
const observer = new QueryObserver(queryClient, {
queryKey: key,
enabled: false,
})
const results: QueryObserverResult<unknown>[] = []
const unsubscribe = observer.subscribe((x) => {
results.push(x)
})
observer.setOptions({ enabled: false, staleTime: 10 })
await queryClient.fetchQuery(key, queryFn)
await sleep(100)
unsubscribe()
expect(queryFn).toHaveBeenCalledTimes(1)
expect(results.length).toBe(3)
expect(results[0]).toMatchObject({ isStale: true })
expect(results[1]).toMatchObject({ isStale: false })
expect(results[2]).toMatchObject({ isStale: true })
})
test('should be able to handle multiple subscribers', async () => {
const key = queryKey()
const queryFn = jest.fn<string, unknown[]>().mockReturnValue('data')
const observer = new QueryObserver<string>(queryClient, {
queryKey: key,
enabled: false,
})
const results1: QueryObserverResult<string>[] = []
const results2: QueryObserverResult<string>[] = []
const unsubscribe1 = observer.subscribe((x) => {
results1.push(x)
})
const unsubscribe2 = observer.subscribe((x) => {
results2.push(x)
})
await queryClient.fetchQuery(key, queryFn)
await sleep(50)
unsubscribe1()
unsubscribe2()
expect(queryFn).toHaveBeenCalledTimes(1)
expect(results1.length).toBe(2)
expect(results2.length).toBe(2)
expect(results1[0]).toMatchObject({ data: undefined })
expect(results1[1]).toMatchObject({ data: 'data' })
expect(results2[0]).toMatchObject({ data: undefined })
expect(results2[1]).toMatchObject({ data: 'data' })
})
test('should stop retry when unsubscribing', async () => {
const key = queryKey()
let count = 0
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => {
count++
return Promise.reject<unknown>('reject')
},
retry: 10,
retryDelay: 50,
})
const unsubscribe = observer.subscribe(() => undefined)
await sleep(70)
unsubscribe()
await sleep(200)
expect(count).toBe(2)
})
test('should clear interval when unsubscribing to a refetchInterval query', async () => {
const key = queryKey()
const fetchData = () => Promise.resolve('data')
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: fetchData,
cacheTime: 0,
refetchInterval: 1,
})
const unsubscribe = observer.subscribe(() => undefined)
// @ts-expect-error
expect(observer.refetchIntervalId).not.toBeUndefined()
unsubscribe()
// @ts-expect-error
expect(observer.refetchIntervalId).toBeUndefined()
await sleep(10)
expect(queryClient.getQueryCache().find(key)).toBeUndefined()
})
test('uses placeholderData as non-cache data when loading a query with no data', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => 'data',
placeholderData: 'placeholder',
})
expect(observer.getCurrentResult()).toMatchObject({
status: 'success',
data: 'placeholder',
})
const results: QueryObserverResult<unknown>[] = []
const unsubscribe = observer.subscribe((x) => {
results.push(x)
})
await sleep(10)
unsubscribe()
expect(results.length).toBe(2)
expect(results[0]).toMatchObject({ status: 'success', data: 'placeholder' })
expect(results[1]).toMatchObject({ status: 'success', data: 'data' })
})
test('the retrier should not throw an error when reject if the retrier is already resolved', async () => {
const key = queryKey()
let count = 0
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => {
count++
return Promise.reject<unknown>(`reject ${count}`)
},
retry: 1,
retryDelay: 20,
})
const unsubscribe = observer.subscribe(() => undefined)
// Simulate a race condition when an unsubscribe and a retry occur.
await sleep(20)
unsubscribe()
// A second reject is triggered for the retry
// but the retryer has already set isResolved to true
// so it does nothing and no error is thrown
// Should not log an error
queryClient.clear()
await sleep(40)
expect(mockLogger.error).not.toHaveBeenNthCalledWith(1, 'reject 1')
})
test('should throw an error if enabled option type is not valid', async () => {
const key = queryKey()
expect(
() =>
new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => 'data',
//@ts-expect-error
enabled: null,
}),
).toThrowError('Expected enabled to be a boolean')
})
test('getCurrentQuery should return the current query', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => 'data',
})
expect(observer.getCurrentQuery().queryKey).toEqual(key)
})
test('should throw an error if throwOnError option is true', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => Promise.reject<unknown>('error'),
retry: false,
})
let error: string | null = null
try {
await observer.refetch({ throwOnError: true })
} catch (err) {
error = err as string
}
expect(error).toEqual('error')
})
test('should not refetch in background if refetchIntervalInBackground is false', async () => {
const key = queryKey()
const queryFn = jest.fn<string, unknown[]>().mockReturnValue('data')
focusManager.setFocused(false)
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
refetchIntervalInBackground: false,
refetchInterval: 10,
})
const unsubscribe = observer.subscribe(() => undefined)
await sleep(30)
expect(queryFn).toHaveBeenCalledTimes(1)
// Clean-up
unsubscribe()
focusManager.setFocused(true)
})
test('should not use replaceEqualDeep for select value when structuralSharing option is true', async () => {
const key = queryKey()
const data = { value: 'data' }
const selectedData = { value: 'data' }
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => data,
select: () => data,
})
const unsubscribe = observer.subscribe(() => undefined)
await sleep(10)
expect(observer.getCurrentResult().data).toBe(data)
observer.setOptions({
queryKey: key,
queryFn: () => data,
structuralSharing: false,
select: () => selectedData,
})
await observer.refetch()
expect(observer.getCurrentResult().data).toBe(selectedData)
unsubscribe()
})
test('should prefer isDataEqual to structuralSharing', async () => {
const key = queryKey()
const data = { value: 'data' }
const newData = { value: 'data' }
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => data,
})
const unsubscribe = observer.subscribe(() => undefined)
await sleep(10)
expect(observer.getCurrentResult().data).toBe(data)
observer.setOptions({
queryKey: key,
queryFn: () => newData,
isDataEqual: () => true,
structuralSharing: false,
})
await observer.refetch()
expect(observer.getCurrentResult().data).toBe(data)
unsubscribe()
})
test('select function error using placeholderdata should log an error', () => {
const key = queryKey()
new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => 'data',
placeholderData: 'placeholderdata',
select: () => {
throw new Error('error')
},
})
expect(mockLogger.error).toHaveBeenNthCalledWith(1, new Error('error'))
})
test('should not use replaceEqualDeep for select value when structuralSharing option is true and placeholderdata is defined', () => {
const key = queryKey()
const data = { value: 'data' }
const selectedData1 = { value: 'data' }
const selectedData2 = { value: 'data' }
const placeholderData1 = { value: 'data' }
const placeholderData2 = { value: 'data' }
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => data,
select: () => data,
})
observer.setOptions({
queryKey: key,
queryFn: () => data,
select: () => {
return selectedData1
},
placeholderData: placeholderData1,
})
observer.setOptions({
queryKey: key,
queryFn: () => data,
select: () => {
return selectedData2
},
placeholderData: placeholderData2,
structuralSharing: false,
})
expect(observer.getCurrentResult().data).toBe(selectedData2)
})
test('should not use an undefined value returned by select as placeholderdata', () => {
const key = queryKey()
const data = { value: 'data' }
const selectedData = { value: 'data' }
const placeholderData1 = { value: 'data' }
const placeholderData2 = { value: 'data' }
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => data,
select: () => data,
})
observer.setOptions({
queryKey: key,
queryFn: () => data,
select: () => {
return selectedData
},
placeholderData: placeholderData1,
})
expect(observer.getCurrentResult().isPlaceholderData).toBe(true)
observer.setOptions({
queryKey: key,
queryFn: () => data,
//@ts-expect-error
select: () => undefined,
placeholderData: placeholderData2,
})
expect(observer.getCurrentResult().isPlaceholderData).toBe(false)
})
test('updateResult should not notify cache listeners if cache option is false', async () => {
const key = queryKey()
const data1 = { value: 'data 1' }
const data2 = { value: 'data 2' }
await queryClient.prefetchQuery(key, () => data1)
const observer = new QueryObserver(queryClient, {
queryKey: key,
})
await queryClient.prefetchQuery(key, () => data2)
const spy = jest.fn()
const unsubscribe = queryClient.getQueryCache().subscribe(spy)
observer.updateResult({ cache: false })
expect(spy).toHaveBeenCalledTimes(0)
unsubscribe()
})
test('should not notify observer when the stale timeout expires and the current result is stale', async () => {
const key = queryKey()
const queryFn = () => 'data'
await queryClient.prefetchQuery(key, queryFn)
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn,
staleTime: 20,
})
const spy = jest.fn()
const unsubscribe = observer.subscribe(spy)
await queryClient.refetchQueries(key)
await sleep(10)
// Force isStale to true
// because no use case has been found to reproduce this condition
// @ts-ignore
observer['currentResult'].isStale = true
spy.mockReset()
await sleep(30)
expect(spy).not.toHaveBeenCalled()
unsubscribe()
})
})