-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathquery.test.ts
More file actions
6490 lines (5442 loc) · 206 KB
/
query.test.ts
File metadata and controls
6490 lines (5442 loc) · 206 KB
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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, hashKey } from '@tanstack/query-core'
import {
BTreeIndex,
createCollection,
createLiveQueryCollection,
eq,
ilike,
inArray,
or,
} from '@tanstack/db'
import { stripVirtualProps } from '../../db/tests/utils'
import { persistedCollectionOptions } from '../../db-sqlite-persistence-core/src'
import { queryCollectionOptions } from '../src/query'
import type { QueryFunctionContext } from '@tanstack/query-core'
import type {
Collection,
DeleteMutationFnParams,
InsertMutationFnParams,
SyncMetadataApi,
TransactionWithMutations,
UpdateMutationFnParams,
} from '@tanstack/db'
import type { QueryCollectionConfig, QueryCollectionUtils } from '../src/query'
interface TestItem {
id: string
name: string
value?: number
}
interface CategorisedItem {
id: string
name: string
category: string
}
const getKey = (item: TestItem) => item.id
// Helper to advance timers and allow microtasks to flush
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0))
function createInMemorySyncMetadataApi<
TKey extends string | number = string | number,
TItem extends object = Record<string, unknown>,
>(seed?: {
rowMetadata?: ReadonlyMap<TKey, unknown>
collectionMetadata?: ReadonlyMap<string, unknown>
persistedRows?: ReadonlyMap<TKey, TItem>
}): {
api: SyncMetadataApi<TKey>
rowMetadata: Map<TKey, unknown>
collectionMetadata: Map<string, unknown>
persistedRows: Map<TKey, TItem>
} {
const rowMetadata = new Map(seed?.rowMetadata)
const collectionMetadata = new Map(seed?.collectionMetadata)
const persistedRows = new Map(seed?.persistedRows)
const api = {
row: {
get: (key: TKey) => rowMetadata.get(key),
set: (key: TKey, value: unknown) => {
rowMetadata.set(key, value)
},
delete: (key: TKey) => {
rowMetadata.delete(key)
},
scanPersisted: async () =>
Array.from(persistedRows.entries()).map(([key, value]) => ({
key,
value,
metadata: rowMetadata.get(key),
})),
},
collection: {
get: (key: string) => collectionMetadata.get(key),
set: (key: string, value: unknown) => {
collectionMetadata.set(key, value)
},
delete: (key: string) => {
collectionMetadata.delete(key)
},
list: (prefix?: string) =>
Array.from(collectionMetadata.entries())
.filter(([key]) => (prefix ? key.startsWith(prefix) : true))
.map(([key, value]) => ({ key, value })),
},
}
return {
rowMetadata,
collectionMetadata,
persistedRows,
api: api as SyncMetadataApi<TKey>,
}
}
function createPersistedQueryAdapter<TItem extends { id: string }>(
seed: {
rows?: ReadonlyMap<string, TItem>
rowMetadata?: ReadonlyMap<string, unknown>
collectionMetadata?: ReadonlyMap<string, unknown>
} = {},
) {
const rows = new Map(seed.rows)
const rowMetadata = new Map(seed.rowMetadata)
const collectionMetadata = new Map(seed.collectionMetadata)
return {
rows,
rowMetadata,
collectionMetadata,
loadSubset: async () =>
Array.from(rows.values()).map((value) => ({
key: value.id,
value,
metadata: rowMetadata.get(value.id),
})),
loadCollectionMetadata: async () =>
Array.from(collectionMetadata.entries()).map(([key, value]) => ({
key,
value,
})),
scanRows: async () =>
Array.from(rows.values()).map((value) => ({
key: value.id,
value,
metadata: rowMetadata.get(value.id),
})),
applyCommittedTx: async (_collectionId: string, tx: any) => {
if (tx.truncate) {
rows.clear()
rowMetadata.clear()
}
for (const mutation of tx.mutations) {
if (mutation.type === `delete`) {
rows.delete(mutation.key)
rowMetadata.delete(mutation.key)
} else {
rows.set(mutation.key, mutation.value)
}
}
for (const mutation of tx.rowMetadataMutations ?? []) {
if (mutation.type === `delete`) {
rowMetadata.delete(mutation.key)
} else {
rowMetadata.set(mutation.key, mutation.value)
}
}
for (const mutation of tx.collectionMetadataMutations ?? []) {
if (mutation.type === `delete`) {
collectionMetadata.delete(mutation.key)
} else {
collectionMetadata.set(mutation.key, mutation.value)
}
}
},
ensureIndex: async () => {},
}
}
describe(`QueryCollection`, () => {
let queryClient: QueryClient
beforeEach(() => {
queryClient = new QueryClient({
defaultOptions: {
queries: {
// Setting a low staleTime and gcTime to ensure queries can be refetched easily in tests
// and GC'd quickly if not observed.
staleTime: 0,
gcTime: 0, // Immediate GC for tests
retry: false, // Disable retries for tests to avoid delays
},
},
})
})
afterEach(() => {
// Ensure all queries are properly cleaned up after each test
queryClient.clear()
})
it(`should initialize and fetch initial data`, async () => {
const queryKey = [`testItems`]
const initialItems: Array<TestItem> = [
{ id: `1`, name: `Item 1` },
{ id: `2`, name: `Item 2` },
]
const queryFn = vi.fn().mockResolvedValue(initialItems)
const config: QueryCollectionConfig<TestItem> = {
id: `test`,
queryClient,
queryKey,
queryFn,
getKey,
startSync: true,
}
const options = queryCollectionOptions(config)
const collection = createCollection(options)
// Wait for the query to complete and collection to update
await vi.waitFor(
() => {
expect(queryFn).toHaveBeenCalledTimes(1)
expect(collection.size).toBeGreaterThan(0)
},
{
timeout: 1000, // Give it a reasonable timeout
interval: 50, // Check frequently
},
)
// Additional wait for internal processing if necessary
await flushPromises()
// Verify the collection state contains our items
expect(collection.size).toBe(initialItems.length)
expect(stripVirtualProps(collection.get(`1`))).toEqual(initialItems[0])
expect(stripVirtualProps(collection.get(`2`))).toEqual(initialItems[1])
// Verify the synced data
expect(collection._state.syncedData.size).toBe(initialItems.length)
expect(collection._state.syncedData.get(`1`)).toEqual(initialItems[0])
expect(collection._state.syncedData.get(`2`)).toEqual(initialItems[1])
})
it(`should update collection when query data changes`, async () => {
const queryKey = [`testItems`]
const initialItems: Array<TestItem> = [
{ id: `1`, name: `Item 1` },
{ id: `2`, name: `Item 2` },
]
// We'll use this to control what the queryFn returns in each call
let currentItems = [...initialItems]
const queryFn = vi
.fn()
.mockImplementation(() => Promise.resolve(currentItems))
const config: QueryCollectionConfig<TestItem> = {
id: `test`,
queryClient,
queryKey,
queryFn,
getKey,
startSync: true,
}
const options = queryCollectionOptions(config)
const collection = createCollection(options)
// Wait for initial data to load
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
expect(collection.size).toBeGreaterThan(0)
})
// Verify initial state
expect(collection.size).toBe(initialItems.length)
expect(stripVirtualProps(collection.get(`1`))).toEqual(initialItems[0])
expect(stripVirtualProps(collection.get(`2`))).toEqual(initialItems[1])
// Now update the data that will be returned by queryFn
// 1. Modify an existing item
// 2. Add a new item
// 3. Remove an existing item
const updatedItem = { id: `1`, name: `Item 1 Updated` }
const newItem = { id: `3`, name: `Item 3` }
currentItems = [
updatedItem, // Modified
newItem, // Added
// Item 2 removed
]
// Refetch the query.
await collection.utils.refetch()
expect(queryFn).toHaveBeenCalledTimes(2)
// Check for update, addition, and removal
expect(collection.size).toBe(2)
expect(collection.has(`1`)).toBe(true)
expect(collection.has(`3`)).toBe(true)
expect(collection.has(`2`)).toBe(false)
// Verify the final state more thoroughly
expect(stripVirtualProps(collection.get(`1`))).toEqual(updatedItem)
expect(stripVirtualProps(collection.get(`3`))).toEqual(newItem)
expect(stripVirtualProps(collection.get(`2`))).toBeUndefined()
// Now update the data again.
const item4 = { id: `4`, name: `Item 4` }
currentItems = [...currentItems, item4]
// Refetch the query to trigger a refetch.
await collection.utils.refetch()
// Verify expected.
expect(queryFn).toHaveBeenCalledTimes(3)
expect(collection.size).toBe(3)
expect(stripVirtualProps(collection.get(`4`))).toEqual(item4)
})
it(`should handle query errors gracefully`, async () => {
const queryKey = [`errorItems`]
const testError = new Error(`Test query error`)
const initialItem = { id: `1`, name: `Initial Item` }
// Mock console.error to verify it's called with our error
const consoleErrorSpy = vi
.spyOn(console, `error`)
.mockImplementation(() => {})
const queryFn: (
context: QueryFunctionContext<any>,
) => Promise<Array<TestItem>> = vi
.fn()
.mockResolvedValueOnce([initialItem])
.mockRejectedValueOnce(testError)
const options = queryCollectionOptions({
id: `test`,
queryClient,
queryKey,
queryFn,
getKey,
startSync: true,
retry: 0, // Disable retries for this test case
})
const collection = createCollection(options)
// Wait for initial data to load
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
expect(collection.size).toBe(1)
expect(stripVirtualProps(collection.get(`1`))).toEqual(initialItem)
})
// Trigger an error by refetching
await collection.utils.refetch()
// Wait for the error to be logged
expect(queryFn).toHaveBeenCalledTimes(2)
expect(consoleErrorSpy).toHaveBeenCalled()
// Verify the error was logged correctly
const errorCallArgs = consoleErrorSpy.mock.calls.find((call) =>
call[0].includes(`[QueryCollection] Error observing query`),
)
expect(errorCallArgs).toBeDefined()
expect(errorCallArgs?.[1]).toBe(testError)
// The collection should maintain its previous state
expect(collection.size).toBe(1)
expect(stripVirtualProps(collection.get(`1`))).toEqual(initialItem)
// Clean up the spy
consoleErrorSpy.mockRestore()
})
it(`should validate that queryFn returns an array of objects`, async () => {
const queryKey = [`invalidData`]
const consoleErrorSpy = vi
.spyOn(console, `error`)
.mockImplementation(() => {})
// Mock queryFn to return invalid data (not an array of objects)
const queryFn: (
context: QueryFunctionContext<any>,
) => Promise<Array<TestItem>> = vi
.fn()
.mockResolvedValue(`not an array` as any)
const options = queryCollectionOptions({
id: `test`,
queryClient,
queryKey,
queryFn,
getKey,
startSync: true,
})
const collection = createCollection(options)
// Wait for the query to execute
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
})
// Verify the validation error was logged
await vi.waitFor(() => {
const errorCallArgs = consoleErrorSpy.mock.calls.find((call) =>
call[0].includes(
`@tanstack/query-db-collection: queryFn must return an array of objects`,
),
)
expect(errorCallArgs).toBeDefined()
})
// The collection state should remain empty or unchanged
expect(collection.size).toBe(0)
// Clean up the spy
consoleErrorSpy.mockRestore()
})
it(`should use shallow equality to avoid unnecessary updates`, async () => {
const queryKey = [`shallowEqualityTest`]
const initialItem = { id: `1`, name: `Test Item`, count: 42 }
// First query returns the initial item
// Second query returns a new object with the same properties (different reference)
// Third query returns an object with an actual change
const queryFn: (
context: QueryFunctionContext<any>,
) => Promise<Array<TestItem>> = vi
.fn()
.mockResolvedValueOnce([initialItem])
.mockResolvedValueOnce([{ ...initialItem }]) // Same data, different object reference
.mockResolvedValueOnce([{ ...initialItem, count: 43 }]) // Actually changed data
// Spy on console.log to detect when commits happen
const consoleSpy = vi.spyOn(console, `log`)
const options = queryCollectionOptions({
id: `test`,
queryClient,
queryKey,
queryFn,
getKey,
startSync: true,
})
const collection = createCollection(options)
// Wait for initial data to load
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
expect(collection.size).toBe(1)
expect(stripVirtualProps(collection.get(`1`))).toEqual(initialItem)
})
// Store the initial state object reference to check if it changes
const initialStateRef = collection.get(`1`)
consoleSpy.mockClear()
// Trigger first refetch - should not cause an update due to shallow equality
await collection.utils.refetch()
expect(queryFn).toHaveBeenCalledTimes(2)
// Since the data is identical (though a different object reference),
// the state object reference should remain the same due to shallow equality
expect(collection.get(`1`)).toBe(initialStateRef) // Same reference
consoleSpy.mockClear()
// Trigger second refetch - should cause an update due to actual data change
await collection.utils.refetch()
expect(queryFn).toHaveBeenCalledTimes(3)
// Now the state should be updated with the new value
const updatedItem = collection.get(`1`)
expect(updatedItem).not.toBe(initialStateRef) // Different reference
expect(stripVirtualProps(updatedItem)).toEqual({
id: `1`,
name: `Test Item`,
count: 43,
}) // Updated value
consoleSpy.mockRestore()
})
it(`should use the provided getKey function to identify items`, async () => {
const queryKey = [`customKeyTest`]
// Items with a non-standard ID field
const items = [
{ customId: `item1`, name: `First Item` },
{ customId: `item2`, name: `Second Item` },
]
const queryFn = vi.fn().mockResolvedValue(items)
// Create a spy for the getKey function
const getKeySpy = vi.fn((item: any) => item.customId)
const options = queryCollectionOptions({
id: `test`,
queryClient,
queryKey,
queryFn,
getKey: getKeySpy,
startSync: true,
})
const collection = createCollection(options)
// Wait for initial data to load
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
expect(collection.size).toBe(items.length)
})
// Verify getKey was called for each item
expect(getKeySpy).toHaveBeenCalledTimes(items.length * 2)
items.forEach((item) => {
expect(getKeySpy).toHaveBeenCalledWith(item)
})
// Verify items are stored with the custom keys
expect(collection.has(`item1`)).toBe(true)
expect(collection.has(`item2`)).toBe(true)
expect(stripVirtualProps(collection.get(`item1`))).toEqual(items[0])
expect(stripVirtualProps(collection.get(`item2`))).toEqual(items[1])
// Now update an item and add a new one
const updatedItems = [
{ customId: `item1`, name: `Updated First Item` }, // Updated
{ customId: `item3`, name: `Third Item` }, // New
// item2 removed
]
// Reset the spy to track new calls
getKeySpy.mockClear()
queryFn.mockResolvedValueOnce(updatedItems)
// Trigger a refetch
await collection.utils.refetch()
expect(queryFn).toHaveBeenCalledTimes(2)
expect(collection.size).toBe(updatedItems.length)
// Verify getKey was called at least once for each item
// It may be called multiple times per item during the diffing process
expect(getKeySpy).toHaveBeenCalled()
updatedItems.forEach((item) => {
expect(getKeySpy).toHaveBeenCalledWith(item)
})
// Verify the state reflects the changes
expect(collection.has(`item1`)).toBe(true)
expect(collection.has(`item2`)).toBe(false) // Removed
expect(collection.has(`item3`)).toBe(true) // Added
expect(stripVirtualProps(collection.get(`item1`))).toEqual(updatedItems[0])
expect(stripVirtualProps(collection.get(`item3`))).toEqual(updatedItems[1])
})
it(`should pass meta property to queryFn context`, async () => {
const queryKey = [`metaTest`]
const meta = { errorMessage: `Failed to load items` }
const queryFn = vi.fn().mockResolvedValueOnce([])
const config: QueryCollectionConfig<TestItem> = {
id: `test`,
queryClient,
queryKey,
queryFn,
getKey,
meta,
startSync: true,
}
const options = queryCollectionOptions(config)
createCollection(options)
// Wait for query to execute
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
})
// Verify queryFn was called with the correct context, including the meta object
expect(queryFn).toHaveBeenCalledWith(
expect.objectContaining({ meta: { ...meta, loadSubsetOptions: {} } }),
)
})
describe(`loadSubsetOptions passed to queryFn`, () => {
it(`should pass eq where clause to queryFn via loadSubsetOptions`, async () => {
const queryKey = [`loadSubsetTest`]
const queryFn = vi
.fn()
.mockImplementation((ctx: QueryFunctionContext<any>) => {
const loadSubsetOptions = ctx.meta?.loadSubsetOptions
// Verify where clause is present
expect(loadSubsetOptions?.where).toBeDefined()
expect(loadSubsetOptions?.where).not.toBeNull()
if (loadSubsetOptions?.where?.type === `func`) {
expect(loadSubsetOptions.where.name).toBe(`eq`)
}
return Promise.resolve([])
})
const config: QueryCollectionConfig<TestItem> = {
id: `loadSubsetTest`,
queryClient,
queryKey,
queryFn,
getKey,
syncMode: `on-demand`,
// startSync: true,
}
const options = queryCollectionOptions(config)
const collection = createCollection(options)
// Create a live query with an eq where clause
const liveQuery = createLiveQueryCollection({
query: (q) =>
q
.from({ item: collection })
.where(({ item }) => eq(item.id, `1`))
.select(({ item }) => ({ id: item.id, name: item.name })),
})
await liveQuery.preload()
// Wait for queryFn to be called
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalled()
})
// Verify queryFn was called with loadSubsetOptions containing the where clause
expect(queryFn).toHaveBeenCalledWith(
expect.objectContaining({
meta: expect.objectContaining({
loadSubsetOptions: expect.objectContaining({
where: expect.objectContaining({
type: `func`,
name: `eq`,
}),
}),
}),
}),
)
})
it(`should pass ilike where clause to queryFn via loadSubsetOptions`, async () => {
const queryFn = vi
.fn()
.mockImplementation((ctx: QueryFunctionContext<any>) => {
const loadSubsetOptions = ctx.meta?.loadSubsetOptions
// Verify where clause is present (this was the bug - it was undefined/null before the fix)
expect(loadSubsetOptions?.where).toBeDefined()
expect(loadSubsetOptions?.where).not.toBeNull()
if (loadSubsetOptions?.where?.type === `func`) {
expect(loadSubsetOptions.where.name).toBe(`ilike`)
}
return Promise.resolve([])
})
const config: QueryCollectionConfig<TestItem> = {
id: `loadSubsetIlikeTest`,
queryClient,
queryKey: [`loadSubsetIlikeTest`],
queryFn,
getKey,
syncMode: `on-demand`,
// startSync: true,
}
const options = queryCollectionOptions(config)
const collection = createCollection(options)
// Create a live query with an ilike where clause
const liveQuery = createLiveQueryCollection({
query: (q) =>
q
.from({ item: collection })
.where(({ item }) => ilike(item.name, `%test%`))
.orderBy(({ item }) => item.name)
.limit(10),
})
await liveQuery.preload()
// Wait for queryFn to be called
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalled()
})
// Verify queryFn was called with loadSubsetOptions containing the ilike where clause
// Without the fix: where would be undefined/null
// With the fix: where should be defined with the ilike expression
expect(queryFn).toHaveBeenCalledWith(
expect.objectContaining({
meta: expect.objectContaining({
loadSubsetOptions: expect.objectContaining({
where: expect.objectContaining({
type: `func`,
name: `ilike`,
}),
}),
}),
}),
)
})
})
describe(`Select method testing`, () => {
type MetaDataType<T> = {
metaDataOne: string
metaDataTwo: string
data: Array<T>
}
const initialMetaData: MetaDataType<TestItem> = {
metaDataOne: `example metadata`,
metaDataTwo: `example metadata`,
data: [
{
id: `1`,
name: `First Item`,
},
{
id: `2`,
name: `Second Item`,
},
],
}
it(`Select extracts array from metadata`, async () => {
const queryKey = [`select-test`]
const queryFn = vi.fn().mockResolvedValue(initialMetaData)
const select = vi.fn().mockReturnValue(initialMetaData.data)
const options = queryCollectionOptions({
id: `test`,
queryClient,
queryKey,
queryFn,
select,
getKey,
startSync: true,
})
const collection = createCollection(options)
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
expect(select).toHaveBeenCalledTimes(1)
expect(collection.size).toBeGreaterThan(0)
})
expect(collection.size).toBe(initialMetaData.data.length)
expect(stripVirtualProps(collection.get(`1`))).toEqual(
initialMetaData.data[0],
)
expect(stripVirtualProps(collection.get(`2`))).toEqual(
initialMetaData.data[1],
)
})
it(`Throws error if select returns non array`, async () => {
const queryKey = [`select-test`]
const consoleErrorSpy = vi
.spyOn(console, `error`)
.mockImplementation(() => {})
const queryFn = vi.fn().mockResolvedValue(initialMetaData)
// Returns non-array
const select = vi.fn().mockReturnValue(initialMetaData)
const options = queryCollectionOptions({
id: `test`,
queryClient,
queryKey,
queryFn,
select,
getKey,
startSync: true,
})
const collection = createCollection(options)
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
expect(select).toHaveBeenCalledTimes(1)
})
// Verify the validation error was logged
await vi.waitFor(() => {
const errorCallArgs = consoleErrorSpy.mock.calls.find((call) =>
call[0].includes(
`@tanstack/query-db-collection: select() must return an array of objects`,
),
)
expect(errorCallArgs).toBeDefined()
})
expect(collection.size).toBe(0)
// Clean up the spy
consoleErrorSpy.mockRestore()
})
it(`Whole response is cached in QueryClient when used with select option`, async () => {
const queryKey = [`select-test`]
const queryFn = vi.fn().mockResolvedValue(initialMetaData)
const select = vi.fn().mockReturnValue(initialMetaData.data)
const options = queryCollectionOptions({
id: `test`,
queryClient,
queryKey,
queryFn,
select,
getKey,
startSync: true,
})
const collection = createCollection(options)
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
expect(select).toHaveBeenCalledTimes(1)
expect(collection.size).toBe(2)
})
// Verify that the query cache state exists along with its metadata
const initialCache = queryClient.getQueryData(
queryKey,
) as MetaDataType<TestItem>
expect(initialCache).toEqual(initialMetaData)
})
it(`should not throw error when using writeInsert with select option`, async () => {
const queryKey = [`select-writeInsert-test`]
const consoleErrorSpy = vi
.spyOn(console, `error`)
.mockImplementation(() => {})
const queryFn = vi.fn().mockResolvedValue(initialMetaData)
const select = vi.fn((data: MetaDataType<TestItem>) => data.data)
const options = queryCollectionOptions({
id: `select-writeInsert-test`,
queryClient,
queryKey,
queryFn,
select,
getKey,
startSync: true,
})
const collection = createCollection(options)
// Wait for collection to be ready
await vi.waitFor(() => {
expect(collection.status).toBe(`ready`)
expect(collection.size).toBe(2)
})
// This should NOT cause an error - but with the bug it does
const newItem: TestItem = { id: `3`, name: `New Item` }
collection.utils.writeInsert(newItem)
// Verify the item was inserted
expect(collection.size).toBe(3)
expect(stripVirtualProps(collection.get(`3`))).toEqual(newItem)
// Wait a tick to allow any async error handlers to run
await flushPromises()
// Verify no error was logged about select returning non-array
const errorCallArgs = consoleErrorSpy.mock.calls.find((call) =>
call[0]?.includes?.(
`@tanstack/query-db-collection: select() must return an array of objects`,
),
)
expect(errorCallArgs).toBeUndefined()
consoleErrorSpy.mockRestore()
})
it(`should not throw error when using writeUpsert with select option`, async () => {
const queryKey = [`select-writeUpsert-test`]
const consoleErrorSpy = vi
.spyOn(console, `error`)
.mockImplementation(() => {})
const queryFn = vi.fn().mockResolvedValue(initialMetaData)
const select = vi.fn((data: MetaDataType<TestItem>) => data.data)
const options = queryCollectionOptions({
id: `select-writeUpsert-test`,
queryClient,
queryKey,
queryFn,
select,
getKey,
startSync: true,
})
const collection = createCollection(options)
// Wait for collection to be ready
await vi.waitFor(() => {
expect(collection.status).toBe(`ready`)
expect(collection.size).toBe(2)
})
// This should NOT cause an error - but with the bug it does
// Test upsert for new item
const newItem: TestItem = { id: `3`, name: `Upserted New Item` }
collection.utils.writeUpsert(newItem)
// Verify the item was inserted
expect(collection.size).toBe(3)
expect(stripVirtualProps(collection.get(`3`))).toEqual(newItem)
// Test upsert for existing item
collection.utils.writeUpsert({ id: `1`, name: `Updated First Item` })
// Verify the item was updated
expect(collection.get(`1`)?.name).toBe(`Updated First Item`)
// Wait a tick to allow any async error handlers to run
await flushPromises()
// Verify no error was logged about select returning non-array
const errorCallArgs = consoleErrorSpy.mock.calls.find((call) =>
call[0]?.includes?.(
`@tanstack/query-db-collection: select() must return an array of objects`,
),
)
expect(errorCallArgs).toBeUndefined()
consoleErrorSpy.mockRestore()
})
it(`should update query cache with wrapped format preserved when using writeInsert with select option`, async () => {
const queryKey = [`select-cache-update-test`]
const queryFn = vi.fn().mockResolvedValue(initialMetaData)
const select = vi.fn((data: MetaDataType<TestItem>) => data.data)
const options = queryCollectionOptions({
id: `select-cache-update-test`,
queryClient,
queryKey,
queryFn,
select,
getKey,
startSync: true,
})
const collection = createCollection(options)
// Wait for collection to be ready
await vi.waitFor(() => {
expect(collection.status).toBe(`ready`)
expect(collection.size).toBe(2)
})
// Verify initial cache has wrapped format
const initialCache = queryClient.getQueryData(
queryKey,
) as MetaDataType<TestItem>
expect(initialCache.metaDataOne).toBe(`example metadata`)
expect(initialCache.metaDataTwo).toBe(`example metadata`)
expect(initialCache.data).toHaveLength(2)
// Insert a new item
const newItem: TestItem = { id: `3`, name: `New Item` }
collection.utils.writeInsert(newItem)
// Verify the cache still has wrapped format with metadata preserved
const cacheAfterInsert = queryClient.getQueryData(
queryKey,
) as MetaDataType<TestItem>
expect(cacheAfterInsert.metaDataOne).toBe(`example metadata`)
expect(cacheAfterInsert.metaDataTwo).toBe(`example metadata`)
expect(cacheAfterInsert.data).toHaveLength(3)
expect(cacheAfterInsert.data).toContainEqual(newItem)
// Update an existing item
collection.utils.writeUpdate({ id: `1`, name: `Updated First Item` })
// Verify the cache still has wrapped format
const cacheAfterUpdate = queryClient.getQueryData(
queryKey,
) as MetaDataType<TestItem>
expect(cacheAfterUpdate.metaDataOne).toBe(`example metadata`)
expect(cacheAfterUpdate.data).toHaveLength(3)
const updatedItem = cacheAfterUpdate.data.find((item) => item.id === `1`)
expect(updatedItem?.name).toBe(`Updated First Item`)
// Delete an item
collection.utils.writeDelete(`2`)
// Verify the cache still has wrapped format
const cacheAfterDelete = queryClient.getQueryData(
queryKey,
) as MetaDataType<TestItem>
expect(cacheAfterDelete.metaDataOne).toBe(`example metadata`)
expect(cacheAfterDelete.data).toHaveLength(2)
expect(cacheAfterDelete.data).not.toContainEqual(
expect.objectContaining({ id: `2` }),
)
})
})