-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathqueryObserver.test.tsx
1271 lines (1092 loc) · 34.3 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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { waitFor } from '@testing-library/dom'
import {
afterEach,
beforeEach,
describe,
expect,
expectTypeOf,
test,
vi,
} from 'vitest'
import { QueryObserver, focusManager } from '..'
import { pendingThenable } from '../thenable'
import { createQueryClient, queryKey, sleep } from './utils'
import type { QueryClient, QueryObserverResult } from '..'
describe('queryObserver', () => {
let queryClient: QueryClient
beforeEach(() => {
queryClient = createQueryClient({
defaultOptions: {
queries: {
experimental_prefetchInRender: true,
},
},
})
queryClient.mount()
})
afterEach(() => {
queryClient.clear()
})
test('should trigger a fetch when subscribed', async () => {
const key = queryKey()
const queryFn = vi
.fn<(...args: Array<unknown>) => string>()
.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 be able to read latest data after subscribing', async () => {
const key = queryKey()
queryClient.setQueryData(key, 'data')
const observer = new QueryObserver(queryClient, {
queryKey: key,
enabled: false,
})
const unsubscribe = observer.subscribe(vi.fn())
expect(observer.getCurrentResult()).toMatchObject({
status: 'success',
data: 'data',
})
unsubscribe()
})
describe('enabled is a callback that initially returns false', () => {
let observer: QueryObserver<string, Error, string, string, Array<string>>
let enabled: boolean
let count: number
let key: Array<string>
beforeEach(() => {
key = queryKey()
count = 0
enabled = false
observer = new QueryObserver(queryClient, {
queryKey: key,
staleTime: Infinity,
enabled: () => enabled,
queryFn: async () => {
await sleep(10)
count++
return 'data'
},
})
})
test('should not fetch on mount', () => {
const unsubscribe = observer.subscribe(vi.fn())
// Has not fetched and is not fetching since its disabled
expect(count).toBe(0)
expect(observer.getCurrentResult()).toMatchObject({
status: 'pending',
fetchStatus: 'idle',
data: undefined,
})
unsubscribe()
})
test('should not be re-fetched when invalidated with refetchType: all', async () => {
const unsubscribe = observer.subscribe(vi.fn())
queryClient.invalidateQueries({ queryKey: key, refetchType: 'all' })
// So we still expect it to not have fetched and not be fetching
expect(count).toBe(0)
expect(observer.getCurrentResult()).toMatchObject({
status: 'pending',
fetchStatus: 'idle',
data: undefined,
})
await waitFor(() => expect(count).toBe(0))
unsubscribe()
})
test('should still trigger a fetch when refetch is called', async () => {
const unsubscribe = observer.subscribe(vi.fn())
expect(enabled).toBe(false)
// Not the same with explicit refetch, this will override enabled and trigger a fetch anyway
observer.refetch()
expect(observer.getCurrentResult()).toMatchObject({
status: 'pending',
fetchStatus: 'fetching',
data: undefined,
})
await waitFor(() => expect(count).toBe(1))
expect(observer.getCurrentResult()).toMatchObject({
status: 'success',
fetchStatus: 'idle',
data: 'data',
})
unsubscribe()
})
test('should fetch if unsubscribed, then enabled returns true, and then re-subscribed', async () => {
let unsubscribe = observer.subscribe(vi.fn())
expect(observer.getCurrentResult()).toMatchObject({
status: 'pending',
fetchStatus: 'idle',
data: undefined,
})
unsubscribe()
enabled = true
unsubscribe = observer.subscribe(vi.fn())
expect(observer.getCurrentResult()).toMatchObject({
status: 'pending',
fetchStatus: 'fetching',
data: undefined,
})
await waitFor(() => expect(count).toBe(1))
unsubscribe()
})
test('should not be re-fetched if not subscribed to after enabled was toggled to true (fetchStatus: "idle")', async () => {
const unsubscribe = observer.subscribe(vi.fn())
// Toggle enabled
enabled = true
unsubscribe()
queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' })
expect(observer.getCurrentResult()).toMatchObject({
status: 'pending',
fetchStatus: 'idle',
data: undefined,
})
expect(count).toBe(0)
})
test('should not be re-fetched if not subscribed to after enabled was toggled to true (fetchStatus: "fetching")', async () => {
const unsubscribe = observer.subscribe(vi.fn())
// Toggle enabled
enabled = true
queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' })
expect(observer.getCurrentResult()).toMatchObject({
status: 'pending',
fetchStatus: 'fetching',
data: undefined,
})
await waitFor(() => expect(count).toBe(1))
unsubscribe()
})
test('should handle that the enabled callback updates the return value', async () => {
const unsubscribe = observer.subscribe(vi.fn())
// Toggle enabled
enabled = true
queryClient.invalidateQueries({ queryKey: key, refetchType: 'inactive' })
// should not refetch since it was active and we only refetch inactive
await waitFor(() => expect(count).toBe(0))
queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' })
// should refetch since it was active and we refetch active
await waitFor(() => expect(count).toBe(1))
// Toggle enabled
enabled = false
// should not refetch since it is not active and we only refetch active
queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' })
await waitFor(() => expect(count).toBe(1))
unsubscribe()
})
})
test('should be able to read latest data when re-subscribing (but not re-fetching)', async () => {
const key = queryKey()
let count = 0
const observer = new QueryObserver(queryClient, {
queryKey: key,
staleTime: Infinity,
queryFn: async () => {
await sleep(10)
count++
return 'data'
},
})
let unsubscribe = observer.subscribe(vi.fn())
// unsubscribe before data comes in
unsubscribe()
expect(count).toBe(0)
expect(observer.getCurrentResult()).toMatchObject({
status: 'pending',
fetchStatus: 'fetching',
data: undefined,
})
await waitFor(() => expect(count).toBe(1))
// re-subscribe after data comes in
unsubscribe = observer.subscribe(vi.fn())
expect(observer.getCurrentResult()).toMatchObject({
status: 'success',
data: 'data',
})
unsubscribe()
})
test('should notify when switching query', async () => {
const key1 = queryKey()
const key2 = queryKey()
const results: Array<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: 'pending' })
expect(results[1]).toMatchObject({ data: 1, status: 'success' })
expect(results[2]).toMatchObject({ data: undefined, status: 'pending' })
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) => {
expectTypeOf(result).toEqualTypeOf<
QueryObserverResult<{ myCount: number }>
>()
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()
expectTypeOf(observerResult.data).toEqualTypeOf<
{ myCount: number } | undefined
>()
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: Array<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: 'pending',
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: Array<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: 'pending',
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: Array<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: 'pending',
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: Array<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: 'pending',
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 = vi
.fn<(...args: Array<unknown>) => string>()
.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 subscribed and disabled by callback', async () => {
const key = queryKey()
const queryFn = vi
.fn<(...args: Array<unknown>) => string>()
.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 = vi
.fn<(...args: Array<unknown>) => string>()
.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 = vi
.fn<(...args: Array<unknown>) => string>()
.mockReturnValue('data')
const callback = vi.fn()
const observer = new QueryObserver(queryClient, {
queryKey: key,
enabled: false,
})
const unsubscribe = observer.subscribe(callback)
await queryClient.fetchQuery({ queryKey: 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 = vi
.fn<(...args: Array<unknown>) => string>()
.mockReturnValue('data')
const observer = new QueryObserver(queryClient, {
queryKey: key,
enabled: false,
})
const results: Array<QueryObserverResult<unknown>> = []
const unsubscribe = observer.subscribe((x) => {
results.push(x)
})
observer.setOptions({ queryKey: key, enabled: false, staleTime: 10 })
await queryClient.fetchQuery({ queryKey: key, queryFn })
await sleep(20)
unsubscribe()
expect(queryFn).toHaveBeenCalledTimes(1)
expect(results.length).toBe(2)
expect(results[0]).toMatchObject({ isStale: false, data: undefined })
expect(results[1]).toMatchObject({ isStale: false, data: 'data' })
})
test('should be able to handle multiple subscribers', async () => {
const key = queryKey()
const queryFn = vi
.fn<(...args: Array<unknown>) => string>()
.mockReturnValue('data')
const observer = new QueryObserver<string>(queryClient, {
queryKey: key,
enabled: false,
})
const results1: Array<QueryObserverResult<string>> = []
const results2: Array<QueryObserverResult<string>> = []
const unsubscribe1 = observer.subscribe((x) => {
results1.push(x)
})
const unsubscribe2 = observer.subscribe((x) => {
results2.push(x)
})
await queryClient.fetchQuery({ queryKey: 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()
let count = 0
const fetchData = () => {
count++
return Promise.resolve('data')
}
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: fetchData,
gcTime: 0,
refetchInterval: 10,
})
const unsubscribe = observer.subscribe(() => undefined)
expect(count).toBe(1)
await sleep(15)
expect(count).toBe(2)
unsubscribe()
await sleep(10)
expect(queryClient.getQueryCache().find({ queryKey: key })).toBeUndefined()
expect(count).toBe(2)
})
test('uses placeholderData as non-cache data when pending 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: Array<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('should structurally share placeholder data', async () => {
const key = queryKey()
const observer = new QueryObserver(queryClient, {
queryKey: key,
enabled: false,
queryFn: () => 'data',
placeholderData: {},
})
const firstData = observer.getCurrentResult().data
observer.setOptions({ queryKey: key, placeholderData: {} })
const secondData = observer.getCurrentResult().data
expect(firstData).toBe(secondData)
})
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 = vi
.fn<(...args: Array<unknown>) => string>()
.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 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('should pass the correct previous queryKey (from prevQuery) to placeholderData function params with select', async () => {
const results: Array<QueryObserverResult> = []
const keys: Array<ReadonlyArray<unknown> | null> = []
const key1 = queryKey()
const key2 = queryKey()
const data1 = { value: 'data1' }
const data2 = { value: 'data2' }
const observer = new QueryObserver(queryClient, {
queryKey: key1,
queryFn: () => data1,
placeholderData: (prev, prevQuery) => {
keys.push(prevQuery?.queryKey || null)
return prev
},
select: (data) => data.value,
})
const unsubscribe = observer.subscribe((result) => {
results.push(result)
})
await sleep(1)
observer.setOptions({
queryKey: key2,
queryFn: () => data2,
placeholderData: (prev, prevQuery) => {
keys.push(prevQuery?.queryKey || null)
return prev
},
select: (data) => data.value,
})