-
Notifications
You must be signed in to change notification settings - Fork 920
/
Copy pathquery.test.ts
2422 lines (2206 loc) · 80.4 KB
/
query.test.ts
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
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { expect } from 'chai';
import { addEqualityMatcher } from '../../util/equality_matcher';
import { Deferred } from '../../util/promise';
import { EventsAccumulator } from '../util/events_accumulator';
import {
addDoc,
and,
Bytes,
collection,
collectionGroup,
deleteDoc,
disableNetwork,
doc,
DocumentChange,
DocumentChangeType,
DocumentData,
documentId,
enableNetwork,
endAt,
endBefore,
GeoPoint,
getDocs,
limit,
limitToLast,
onSnapshot,
or,
orderBy,
query,
QuerySnapshot,
setDoc,
startAfter,
startAt,
Timestamp,
updateDoc,
where,
writeBatch,
CollectionReference,
WriteBatch,
Firestore,
getDocsFromServer
} from '../util/firebase_export';
import {
apiDescribe,
RetryError,
toChangesArray,
toDataArray,
PERSISTENCE_MODE_UNSPECIFIED,
withEmptyTestCollection,
withRetry,
withTestCollection,
withTestDb,
checkOnlineAndOfflineResultsMatch,
toIds
} from '../util/helpers';
import { USE_EMULATOR } from '../util/settings';
import { captureExistenceFilterMismatches } from '../util/testing_hooks_util';
apiDescribe('Queries', persistence => {
addEqualityMatcher();
it('can issue limit queries', () => {
const testDocs = {
a: { k: 'a' },
b: { k: 'b' },
c: { k: 'c' }
};
return withTestCollection(persistence, testDocs, collection => {
return getDocs(query(collection, limit(2))).then(docs => {
expect(toDataArray(docs)).to.deep.equal([{ k: 'a' }, { k: 'b' }]);
});
});
});
it('cannot issue limitToLast queries without explicit order-by', () => {
return withTestCollection(persistence, {}, async collection => {
const expectedError =
'limitToLast() queries require specifying at least one orderBy() clause';
expect(() => getDocs(query(collection, limitToLast(2)))).to.throw(
expectedError
);
});
});
it('can issue limit queries using descending sort order', () => {
const testDocs = {
a: { k: 'a', sort: 0 },
b: { k: 'b', sort: 1 },
c: { k: 'c', sort: 1 },
d: { k: 'd', sort: 2 }
};
return withTestCollection(persistence, testDocs, collection => {
return getDocs(query(collection, orderBy('sort', 'desc'), limit(2))).then(
docs => {
expect(toDataArray(docs)).to.deep.equal([
{ k: 'd', sort: 2 },
{ k: 'c', sort: 1 }
]);
}
);
});
});
it('can issue limitToLast queries using descending sort order', () => {
const testDocs = {
a: { k: 'a', sort: 0 },
b: { k: 'b', sort: 1 },
c: { k: 'c', sort: 1 },
d: { k: 'd', sort: 2 }
};
return withTestCollection(persistence, testDocs, collection => {
return getDocs(
query(collection, orderBy('sort', 'desc'), limitToLast(2))
).then(docs => {
expect(toDataArray(docs)).to.deep.equal([
{ k: 'b', sort: 1 },
{ k: 'a', sort: 0 }
]);
});
});
});
it('can listen to limitToLast queries', () => {
const testDocs = {
a: { k: 'a', sort: 0 },
b: { k: 'b', sort: 1 },
c: { k: 'c', sort: 1 },
d: { k: 'd', sort: 2 }
};
return withTestCollection(persistence, testDocs, async collection => {
const storeEvent = new EventsAccumulator<QuerySnapshot>();
onSnapshot(
query(collection, orderBy('sort', 'desc'), limitToLast(2)),
storeEvent.storeEvent
);
let snapshot = await storeEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'b', sort: 1 },
{ k: 'a', sort: 0 }
]);
await addDoc(collection, { k: 'e', sort: -1 });
snapshot = await storeEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'a', sort: 0 },
{ k: 'e', sort: -1 }
]);
});
});
// Two queries that mapped to the same target ID are referred to as
// "mirror queries". An example for a mirror query is a limitToLast()
// query and a limit() query that share the same backend Target ID.
// Since limitToLast() queries are sent to the backend with a modified
// orderBy() clause, they can map to the same target representation as
// limit() query, even if both queries appear separate to the user.
it('can listen/unlisten/relisten to mirror queries', () => {
const testDocs = {
a: { k: 'a', sort: 0 },
b: { k: 'b', sort: 1 },
c: { k: 'c', sort: 1 },
d: { k: 'd', sort: 2 }
};
return withTestCollection(persistence, testDocs, async collection => {
// Setup `limit` query
const storeLimitEvent = new EventsAccumulator<QuerySnapshot>();
const limitUnlisten = onSnapshot(
query(collection, orderBy('sort', 'asc'), limit(2)),
storeLimitEvent.storeEvent
);
// Setup mirroring `limitToLast` query
const storeLimitToLastEvent = new EventsAccumulator<QuerySnapshot>();
const limitToLastUnlisten = onSnapshot(
query(collection, orderBy('sort', 'desc'), limitToLast(2)),
storeLimitToLastEvent.storeEvent
);
// Verify both queries get expected results.
let snapshot = await storeLimitEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'a', sort: 0 },
{ k: 'b', sort: 1 }
]);
snapshot = await storeLimitToLastEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'b', sort: 1 },
{ k: 'a', sort: 0 }
]);
// Unlisten then relisten limit query.
limitUnlisten();
onSnapshot(
query(collection, orderBy('sort', 'asc'), limit(2)),
storeLimitEvent.storeEvent
);
// Verify `limit` query still works.
snapshot = await storeLimitEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'a', sort: 0 },
{ k: 'b', sort: 1 }
]);
// Add a document that would change the result set.
await addDoc(collection, { k: 'e', sort: -1 });
// Verify both queries get expected results.
snapshot = await storeLimitEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'e', sort: -1 },
{ k: 'a', sort: 0 }
]);
snapshot = await storeLimitToLastEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'a', sort: 0 },
{ k: 'e', sort: -1 }
]);
// Unlisten to limitToLast, update a doc, then relisten limitToLast.
limitToLastUnlisten();
await updateDoc(doc(collection, 'a'), { k: 'a', sort: -2 });
onSnapshot(
query(collection, orderBy('sort', 'desc'), limitToLast(2)),
storeLimitToLastEvent.storeEvent
);
// Verify both queries get expected results.
snapshot = await storeLimitEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'a', sort: -2 },
{ k: 'e', sort: -1 }
]);
snapshot = await storeLimitToLastEvent.awaitEvent();
expect(toDataArray(snapshot)).to.deep.equal([
{ k: 'e', sort: -1 },
{ k: 'a', sort: -2 }
]);
});
});
it('can issue limitToLast queries with cursors', () => {
const testDocs = {
a: { k: 'a', sort: 0 },
b: { k: 'b', sort: 1 },
c: { k: 'c', sort: 1 },
d: { k: 'd', sort: 2 }
};
return withTestCollection(persistence, testDocs, async collection => {
let docs = await getDocs(
query(collection, orderBy('sort'), endBefore(2), limitToLast(3))
);
expect(toDataArray(docs)).to.deep.equal([
{ k: 'a', sort: 0 },
{ k: 'b', sort: 1 },
{ k: 'c', sort: 1 }
]);
docs = await getDocs(
query(collection, orderBy('sort'), endAt(1), limitToLast(3))
);
expect(toDataArray(docs)).to.deep.equal([
{ k: 'a', sort: 0 },
{ k: 'b', sort: 1 },
{ k: 'c', sort: 1 }
]);
docs = await getDocs(
query(collection, orderBy('sort'), startAt(2), limitToLast(3))
);
expect(toDataArray(docs)).to.deep.equal([{ k: 'd', sort: 2 }]);
docs = await getDocs(
query(collection, orderBy('sort'), startAfter(0), limitToLast(3))
);
expect(toDataArray(docs)).to.deep.equal([
{ k: 'b', sort: 1 },
{ k: 'c', sort: 1 },
{ k: 'd', sort: 2 }
]);
docs = await getDocs(
query(collection, orderBy('sort'), startAfter(-1), limitToLast(3))
);
expect(toDataArray(docs)).to.deep.equal([
{ k: 'b', sort: 1 },
{ k: 'c', sort: 1 },
{ k: 'd', sort: 2 }
]);
});
});
it('key order is descending for descending inequality', () => {
const testDocs = {
a: {
foo: 42
},
b: {
foo: 42.0
},
c: {
foo: 42
},
d: {
foo: 21
},
e: {
foo: 21
},
f: {
foo: 66
},
g: {
foo: 66
}
};
return withTestCollection(persistence, testDocs, coll => {
return getDocs(
query(coll, where('foo', '>', 21.0), orderBy('foo', 'desc'))
).then(docs => {
expect(docs.docs.map(d => d.id)).to.deep.equal([
'g',
'f',
'c',
'b',
'a'
]);
});
});
});
it('can use unary filters', () => {
const testDocs = {
a: { null: null, nan: NaN },
b: { null: null, nan: 0 },
c: { null: false, nan: NaN }
};
return withTestCollection(persistence, testDocs, coll => {
return getDocs(
query(coll, where('null', '==', null), where('nan', '==', NaN))
).then(docs => {
expect(toDataArray(docs)).to.deep.equal([{ null: null, nan: NaN }]);
});
});
});
it('can filter on infinity', () => {
const testDocs = {
a: { inf: Infinity },
b: { inf: -Infinity }
};
return withTestCollection(persistence, testDocs, coll => {
return getDocs(query(coll, where('inf', '==', Infinity))).then(docs => {
expect(toDataArray(docs)).to.deep.equal([{ inf: Infinity }]);
});
});
});
it('will not get metadata only updates', () => {
const testDocs = { a: { v: 'a' }, b: { v: 'b' } };
return withTestCollection(persistence, testDocs, coll => {
const storeEvent = new EventsAccumulator<QuerySnapshot>();
let unlisten: (() => void) | null = null;
return Promise.all([
setDoc(doc(coll, 'a'), { v: 'a' }),
setDoc(doc(coll, 'b'), { v: 'b' })
])
.then(() => {
unlisten = onSnapshot(coll, storeEvent.storeEvent);
return storeEvent.awaitEvent();
})
.then(querySnap => {
expect(toDataArray(querySnap)).to.deep.equal([
{ v: 'a' },
{ v: 'b' }
]);
return setDoc(doc(coll, 'a'), { v: 'a1' });
})
.then(() => storeEvent.awaitEvent())
.then(querySnap => {
expect(toDataArray(querySnap)).to.deep.equal([
{ v: 'a1' },
{ v: 'b' }
]);
return storeEvent.assertNoAdditionalEvents();
})
.then(() => unlisten!());
});
});
it('maintains correct DocumentChange indexes', async () => {
const testDocs = {
'a': { order: 1 },
'b': { order: 2 },
'c': { 'order': 3 }
};
await withTestCollection(persistence, testDocs, async coll => {
const accumulator = new EventsAccumulator<QuerySnapshot>();
const unlisten = onSnapshot(
query(coll, orderBy('order')),
accumulator.storeEvent
);
await accumulator
.awaitEvent()
.then(querySnapshot => {
const changes = querySnapshot.docChanges();
expect(changes.length).to.equal(3);
verifyDocumentChange(changes[0], 'a', -1, 0, 'added');
verifyDocumentChange(changes[1], 'b', -1, 1, 'added');
verifyDocumentChange(changes[2], 'c', -1, 2, 'added');
})
.then(() => setDoc(doc(coll, 'b'), { order: 4 }))
.then(() => accumulator.awaitEvent())
.then(querySnapshot => {
const changes = querySnapshot.docChanges();
expect(changes.length).to.equal(1);
verifyDocumentChange(changes[0], 'b', 1, 2, 'modified');
})
.then(() => deleteDoc(doc(coll, 'c')))
.then(() => accumulator.awaitEvent())
.then(querySnapshot => {
const changes = querySnapshot.docChanges();
expect(changes.length).to.equal(1);
verifyDocumentChange(changes[0], 'c', 1, -1, 'removed');
});
unlisten();
});
});
// TODO(b/295872012): This test is skipped due to the flakiness around the
// checks of hasPendingWrites.
// We should investigate if this is an actual bug.
// eslint-disable-next-line no-restricted-properties
it.skip('can listen for the same query with different options', () => {
const testDocs = { a: { v: 'a' }, b: { v: 'b' } };
return withTestCollection(persistence, testDocs, coll => {
const storeEvent = new EventsAccumulator<QuerySnapshot>();
const storeEventFull = new EventsAccumulator<QuerySnapshot>();
const unlisten1 = onSnapshot(coll, storeEvent.storeEvent);
const unlisten2 = onSnapshot(
coll,
{ includeMetadataChanges: true },
storeEventFull.storeEvent
);
return storeEvent
.awaitEvent()
.then(querySnap => {
expect(toDataArray(querySnap)).to.deep.equal([
{ v: 'a' },
{ v: 'b' }
]);
return storeEventFull.awaitEvent();
})
.then(async querySnap => {
expect(toDataArray(querySnap)).to.deep.equal([
{ v: 'a' },
{ v: 'b' }
]);
if (querySnap.metadata.fromCache) {
// We might receive an additional event if the first query snapshot
// was served from cache.
await storeEventFull.awaitEvent();
}
return setDoc(doc(coll, 'a'), { v: 'a1' });
})
.then(() => {
return storeEventFull.awaitEvents(2);
})
.then(events => {
// Expect two events for the write, once from latency compensation
// and once from the acknowledgment from the server.
expect(toDataArray(events[0])).to.deep.equal([
{ v: 'a1' },
{ v: 'b' }
]);
expect(toDataArray(events[1])).to.deep.equal([
{ v: 'a1' },
{ v: 'b' }
]);
const localResult = events[0].docs;
expect(localResult[0].metadata.hasPendingWrites).to.equal(true);
const syncedResults = events[1].docs;
expect(syncedResults[0].metadata.hasPendingWrites).to.equal(false);
return storeEvent.awaitEvent();
})
.then(querySnap => {
// Expect only one event for the write.
expect(toDataArray(querySnap)).to.deep.equal([
{ v: 'a1' },
{ v: 'b' }
]);
return storeEvent.assertNoAdditionalEvents();
})
.then(() => {
storeEvent.allowAdditionalEvents();
return setDoc(doc(coll, 'b'), { v: 'b1' });
})
.then(() => {
return storeEvent.awaitEvent();
})
.then(querySnap => {
// Expect only one event from the second write
expect(toDataArray(querySnap)).to.deep.equal([
{ v: 'a1' },
{ v: 'b1' }
]);
return storeEventFull.awaitEvents(2);
})
.then(events => {
// Expect 2 events from the second write.
expect(toDataArray(events[0])).to.deep.equal([
{ v: 'a1' },
{ v: 'b1' }
]);
expect(toDataArray(events[1])).to.deep.equal([
{ v: 'a1' },
{ v: 'b1' }
]);
const localResults = events[0].docs;
expect(localResults[1].metadata.hasPendingWrites).to.equal(true);
const syncedResults = events[1].docs;
expect(syncedResults[1].metadata.hasPendingWrites).to.equal(false);
return storeEvent.assertNoAdditionalEvents();
})
.then(() => {
return storeEventFull.assertNoAdditionalEvents();
})
.then(() => {
unlisten1!();
unlisten2!();
});
});
});
it('can issue queries with Dates differing in milliseconds', () => {
const date1 = new Date();
date1.setMilliseconds(0);
const date2 = new Date(date1.getTime());
date2.setMilliseconds(1);
const date3 = new Date(date1.getTime());
date3.setMilliseconds(2);
const testDocs = {
'1': { id: '1', date: date1 },
'2': { id: '2', date: date2 },
'3': { id: '3', date: date3 }
};
return withTestCollection(persistence, testDocs, coll => {
// Make sure to issue the queries in parallel
const docs1Promise = getDocs(query(coll, where('date', '>', date1)));
const docs2Promise = getDocs(query(coll, where('date', '>', date2)));
return Promise.all([docs1Promise, docs2Promise]).then(results => {
const docs1 = results[0];
const docs2 = results[1];
expect(toDataArray(docs1)).to.deep.equal([
{ id: '2', date: Timestamp.fromDate(date2) },
{ id: '3', date: Timestamp.fromDate(date3) }
]);
expect(toDataArray(docs2)).to.deep.equal([
{ id: '3', date: Timestamp.fromDate(date3) }
]);
});
});
});
it('can listen for QueryMetadata changes', () => {
const testDocs = {
'1': { sort: 1, filter: true, key: '1' },
'2': { sort: 2, filter: true, key: '2' },
'3': { sort: 2, filter: true, key: '3' },
'4': { sort: 3, filter: false, key: '4' }
};
return withTestCollection(persistence, testDocs, coll => {
const query1 = query(coll, where('key', '<', '4'));
const accum = new EventsAccumulator<QuerySnapshot>();
let unlisten2: () => void;
const unlisten1 = onSnapshot(query1, result => {
expect(toDataArray(result)).to.deep.equal([
testDocs[1],
testDocs[2],
testDocs[3]
]);
const query2 = query(coll, where('filter', '==', true));
unlisten2 = onSnapshot(
query2,
{
includeMetadataChanges: true
},
accum.storeEvent
);
});
return accum.awaitEvents(2).then(events => {
const results1 = events[0];
const results2 = events[1];
expect(toDataArray(results1)).to.deep.equal([
testDocs[1],
testDocs[2],
testDocs[3]
]);
expect(toDataArray(results1)).to.deep.equal(toDataArray(results2));
expect(results1.metadata.fromCache).to.equal(true);
expect(results2.metadata.fromCache).to.equal(false);
unlisten1();
unlisten2();
});
});
});
it('can listen for metadata changes', () => {
const initialDoc = {
foo: { a: 'b', v: 1 }
};
const modifiedDoc = {
foo: { a: 'b', v: 2 }
};
return withTestCollection(persistence, initialDoc, async coll => {
const accum = new EventsAccumulator<QuerySnapshot>();
const unlisten = onSnapshot(
coll,
{ includeMetadataChanges: true },
accum.storeEvent
);
await accum.awaitEvents(1).then(events => {
const results1 = events[0];
expect(toDataArray(results1)).to.deep.equal([initialDoc['foo']]);
});
// eslint-disable-next-line @typescript-eslint/no-floating-promises
setDoc(doc(coll, 'foo'), modifiedDoc['foo']);
await accum.awaitEvents(2).then(events => {
const results1 = events[0];
expect(toDataArray(results1)).to.deep.equal([modifiedDoc['foo']]);
expect(toChangesArray(results1)).to.deep.equal([modifiedDoc['foo']]);
const results2 = events[1];
expect(toDataArray(results2)).to.deep.equal([modifiedDoc['foo']]);
expect(toChangesArray(results2)).to.deep.equal([]);
expect(
toChangesArray(results2, { includeMetadataChanges: true })
).to.deep.equal([modifiedDoc['foo']]);
});
unlisten();
});
});
// eslint-disable-next-line no-restricted-properties
(USE_EMULATOR ? it.skip : it)(
'can catch error message for missing index with error handler',
() => {
return withEmptyTestCollection(persistence, async coll => {
const query_ = query(
coll,
where('sort', '<=', '2'),
where('filter', '==', true)
);
const deferred = new Deferred<void>();
const unsubscribe = onSnapshot(
query_,
() => {
deferred.reject();
},
err => {
expect(err.code).to.equal('failed-precondition');
expect(err.message).to.exist;
if (coll.firestore._databaseId.isDefaultDatabase) {
expect(err.message).to.match(
/index.*https:\/\/console\.firebase\.google\.com/
);
}
deferred.resolve();
}
);
await deferred.promise;
unsubscribe();
});
}
);
it('can explicitly sort by document ID', () => {
const testDocs = {
a: { key: 'a' },
b: { key: 'b' },
c: { key: 'c' }
};
return withTestCollection(persistence, testDocs, coll => {
// Ideally this would be descending to validate it's different than
// the default, but that requires an extra index
return getDocs(query(coll, orderBy(documentId()))).then(docs => {
expect(toDataArray(docs)).to.deep.equal([
testDocs['a'],
testDocs['b'],
testDocs['c']
]);
});
});
});
it('can query by document ID', () => {
const testDocs = {
aa: { key: 'aa' },
ab: { key: 'ab' },
ba: { key: 'ba' },
bb: { key: 'bb' }
};
return withTestCollection(persistence, testDocs, coll => {
return getDocs(query(coll, where(documentId(), '==', 'ab')))
.then(docs => {
expect(toDataArray(docs)).to.deep.equal([testDocs['ab']]);
return getDocs(
query(
coll,
where(documentId(), '>', 'aa'),
where(documentId(), '<=', 'ba')
)
);
})
.then(docs => {
expect(toDataArray(docs)).to.deep.equal([
testDocs['ab'],
testDocs['ba']
]);
});
});
});
it('can query by document ID using refs', () => {
const testDocs = {
aa: { key: 'aa' },
ab: { key: 'ab' },
ba: { key: 'ba' },
bb: { key: 'bb' }
};
return withTestCollection(persistence, testDocs, coll => {
return getDocs(query(coll, where(documentId(), '==', doc(coll, 'ab'))))
.then(docs => {
expect(toDataArray(docs)).to.deep.equal([testDocs['ab']]);
return getDocs(
query(
coll,
where(documentId(), '>', doc(coll, 'aa')),
where(documentId(), '<=', doc(coll, 'ba'))
)
);
})
.then(docs => {
expect(toDataArray(docs)).to.deep.equal([
testDocs['ab'],
testDocs['ba']
]);
});
});
});
it('can query while reconnecting to network', () => {
return withTestCollection(persistence, /* docs= */ {}, (coll, db) => {
const deferred = new Deferred<void>();
const unregister = onSnapshot(
coll,
{ includeMetadataChanges: true },
snapshot => {
if (!snapshot.empty && !snapshot.metadata.fromCache) {
deferred.resolve();
}
}
);
void disableNetwork(db).then(() => {
void setDoc(doc(coll), { a: 1 });
void enableNetwork(db);
});
return deferred.promise.then(unregister);
});
});
it('trigger with isFromCache=true when offline', () => {
return withTestCollection(persistence, { a: { foo: 1 } }, (coll, db) => {
const accum = new EventsAccumulator<QuerySnapshot>();
const unregister = onSnapshot(
coll,
{ includeMetadataChanges: true },
accum.storeEvent
);
return accum
.awaitEvent()
.then(querySnap => {
// initial event
expect(querySnap.docs.map(doc => doc.data())).to.deep.equal([
{ foo: 1 }
]);
expect(querySnap.metadata.fromCache).to.be.false;
})
.then(() => disableNetwork(db))
.then(() => accum.awaitEvent())
.then(querySnap => {
// offline event with fromCache = true
expect(querySnap.metadata.fromCache).to.be.true;
})
.then(() => enableNetwork(db))
.then(() => accum.awaitEvent())
.then(querySnap => {
// back online event with fromCache = false
expect(querySnap.metadata.fromCache).to.be.false;
unregister();
});
});
});
it('can use != filters', async () => {
// These documents are ordered by value in "zip" since the '!=' filter is
// an inequality, which results in documents being sorted by value.
const testDocs = {
a: { zip: Number.NaN },
b: { zip: 91102 },
c: { zip: 98101 },
d: { zip: '98101' },
e: { zip: [98101] },
f: { zip: [98101, 98102] },
g: { zip: ['98101', { zip: 98101 }] },
h: { zip: { code: 500 } },
i: { code: 500 },
j: { zip: null }
};
await withTestCollection(persistence, testDocs, async coll => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let expected: { [name: string]: any } = { ...testDocs };
delete expected.c;
delete expected.i;
delete expected.j;
const snapshot = await getDocs(query(coll, where('zip', '!=', 98101)));
expect(toDataArray(snapshot)).to.deep.equal(Object.values(expected));
// With objects.
const snapshot2 = await getDocs(
query(coll, where('zip', '!=', { code: 500 }))
);
expected = { ...testDocs };
delete expected.h;
delete expected.i;
delete expected.j;
expect(toDataArray(snapshot2)).to.deep.equal(Object.values(expected));
// With null.
const snapshot3 = await getDocs(query(coll, where('zip', '!=', null)));
expected = { ...testDocs };
delete expected.i;
delete expected.j;
expect(toDataArray(snapshot3)).to.deep.equal(Object.values(expected));
// With NaN.
const snapshot4 = await getDocs(
query(coll, where('zip', '!=', Number.NaN))
);
expected = { ...testDocs };
delete expected.a;
delete expected.i;
delete expected.j;
expect(toDataArray(snapshot4)).to.deep.equal(Object.values(expected));
});
});
it('can use != filters by document ID', async () => {
const testDocs = {
aa: { key: 'aa' },
ab: { key: 'ab' },
ba: { key: 'ba' },
bb: { key: 'bb' }
};
await withTestCollection(persistence, testDocs, async coll => {
const snapshot = await getDocs(
query(coll, where(documentId(), '!=', 'aa'))
);
expect(toDataArray(snapshot)).to.deep.equal([
{ key: 'ab' },
{ key: 'ba' },
{ key: 'bb' }
]);
});
});
it('can use array-contains filters', async () => {
const testDocs = {
a: { array: [42] },
b: { array: ['a', 42, 'c'] },
c: { array: [41.999, '42', { a: [42] }] },
d: { array: [42], array2: ['bingo'] },
e: { array: [null] },
f: { array: [Number.NaN] }
};
await withTestCollection(persistence, testDocs, async coll => {
// Search for 42
const snapshot = await getDocs(
query(coll, where('array', 'array-contains', 42))
);
expect(toDataArray(snapshot)).to.deep.equal([
{ array: [42] },
{ array: ['a', 42, 'c'] },
{ array: [42], array2: ['bingo'] }
]);
// NOTE: The backend doesn't currently support null, NaN, objects, or
// arrays, so there isn't much of anything else interesting to test.
// With null.
const snapshot3 = await getDocs(
query(coll, where('zip', 'array-contains', null))
);
expect(toDataArray(snapshot3)).to.deep.equal([]);
// With NaN.
const snapshot4 = await getDocs(
query(coll, where('zip', 'array-contains', Number.NaN))
);
expect(toDataArray(snapshot4)).to.deep.equal([]);
});
});
it('can use IN filters', async () => {
const testDocs = {
a: { zip: 98101 },
b: { zip: 91102 },
c: { zip: 98103 },
d: { zip: [98101] },
e: { zip: ['98101', { zip: 98101 }] },
f: { zip: { code: 500 } },
g: { zip: [98101, 98102] },
h: { zip: null },
i: { zip: Number.NaN }
};
await withTestCollection(persistence, testDocs, async coll => {
const snapshot = await getDocs(
query(coll, where('zip', 'in', [98101, 98103, [98101, 98102]]))
);
expect(toDataArray(snapshot)).to.deep.equal([
{ zip: 98101 },
{ zip: 98103 },
{ zip: [98101, 98102] }
]);
// With objects.
const snapshot2 = await getDocs(
query(coll, where('zip', 'in', [{ code: 500 }]))
);
expect(toDataArray(snapshot2)).to.deep.equal([{ zip: { code: 500 } }]);
// With null.
const snapshot3 = await getDocs(query(coll, where('zip', 'in', [null])));
expect(toDataArray(snapshot3)).to.deep.equal([]);
// With null and a value.
const snapshot4 = await getDocs(
query(coll, where('zip', 'in', [98101, null]))
);
expect(toDataArray(snapshot4)).to.deep.equal([{ zip: 98101 }]);
// With NaN.
const snapshot5 = await getDocs(
query(coll, where('zip', 'in', [Number.NaN]))
);
expect(toDataArray(snapshot5)).to.deep.equal([]);
// With NaN and a value.
const snapshot6 = await getDocs(
query(coll, where('zip', 'in', [98101, Number.NaN]))
);
expect(toDataArray(snapshot6)).to.deep.equal([{ zip: 98101 }]);
});
});
it('can use IN filters by document ID', async () => {