Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { createCollection, createTransaction } from '@tanstack/db'
3import {
4 addRxPlugin,
5 createRxDatabase,
6 getFromMapOrCreate,
7} from 'rxdb/plugins/core'
8import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode'
9import { getRxStorageMemory } from 'rxdb/plugins/storage-memory'
10import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv'
11import { Subject } from 'rxjs'
12import { stripVirtualProps } from '../../db/tests/utils'
13import { OPEN_RXDB_SUBSCRIPTIONS, rxdbCollectionOptions } from '../src/rxdb'
14import type { RxCollection } from 'rxdb/plugins/core'
15import type { RxDBCollectionConfig } from '../src/rxdb'
16
17type TestDocType = {
18 id: string
19 name: string
20}
21type RxCollections = { test: RxCollection<TestDocType> }
22
23// Helper to advance timers and allow microtasks to flush
24const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0))
25
26function createDeferred<T>() {
27 let resolve!: (value: T) => void
28 const promise = new Promise<T>((resolvePromise) => {
29 resolve = resolvePromise
30 })
31 return { promise, resolve }
32}
33
34describe(`RxDB Integration`, () => {
35 addRxPlugin(RxDBDevModePlugin)
36
37 let dbNameId = 0
38 function getTestData(amount: number): Array<TestDocType> {
39 return new Array(amount).fill(0).map((_v, i) => {
40 return {
41 id: i + 1 + ``,
42 name: `Item ` + (i + 1),
43 }
44 })
45 }
46
47 async function getDatababase(
48 initialDocs: Array<TestDocType> = [],
49 dbId = dbNameId++,
50 ) {
51 const db = await createRxDatabase<RxCollections, unknown, unknown, unknown>(
52 {
53 name: `my-rxdb-` + dbId,
54 ignoreDuplicate: true,
55 storage: wrappedValidateAjvStorage({
56 storage: getRxStorageMemory(),
57 }),
58 },
59 )
60 const collections = await db.addCollections<RxCollections>({
61 test: {
62 schema: {
63 version: 0,
64 type: `object`,
65 primaryKey: `id`,
66 properties: {
67 id: {
68 type: `string`,
69 maxLength: 100,
70 },
71 name: {
72 type: `string`,
73 maxLength: 9,
74 },
75 },
76 },
77 },
78 })
79 const rxCollection: RxCollection<TestDocType> = collections.test
80 if (initialDocs.length > 0) {
81 const insertResult = await rxCollection.bulkInsert(initialDocs)
82 expect(insertResult.error.length).toBe(0)
83 }
84 return db
85 }
86
87 async function createTestState(
88 initialDocs: Array<TestDocType> = [],
89 config: Partial<RxDBCollectionConfig<TestDocType, any>> = {},
90 ) {
91 const db = await getDatababase(initialDocs, dbNameId++)
92 const rxCollection: RxCollection<TestDocType> = db.test
93 const options = rxdbCollectionOptions({
94 rxCollection: rxCollection,
95 startSync: true,
96 /**
97 * In tests we use a small batch size
98 * to ensure iteration works.
99 */
100 syncBatchSize: 10,
101 ...config,
102 })
103
104 const collection = createCollection(options)
105 await collection.stateWhenReady()
106
107 return {
108 collection,
109 rxCollection,
110 db,
111 }
112 }
113
114 describe(`sync`, () => {
115 it(`reports an initial storage query failure`, async () => {
116 const db = await getDatababase()
117 const rxCollection: RxCollection<TestDocType> = db.test
118 const initialError = new Error(`initial RxDB query failed`)
119 const query = vi
120 .spyOn(rxCollection.storageInstance, `query`)
121 .mockRejectedValueOnce(initialError)
122 const collection = createCollection(
123 rxdbCollectionOptions({
124 rxCollection,
125 startSync: true,
126 syncBatchSize: 10,
127 }),
128 )
129
130 try {
131 await expect(collection.preload()).rejects.toBe(initialError)
132 expect(collection.status).toBe(`error`)
133 expect(OPEN_RXDB_SUBSCRIPTIONS.get(rxCollection)?.size ?? 0).toBe(0)
134
135 await rxCollection.insert({ id: `after-failure`, name: `failed` })
136 await flushPromises()
137 expect(OPEN_RXDB_SUBSCRIPTIONS.get(rxCollection)?.size ?? 0).toBe(0)
138 expect(collection.has(`after-failure`)).toBe(false)
139 } finally {
140 query.mockRestore()
141 await collection.cleanup()
142 await db.remove()
143 }
144 })
145
146 // A reload runs `sync` again while the Collection still shows `error`.
147 // The new run's readiness, not that status, decides its outcome.
148 it.each([`ok`, `fail`] as const)(
149 `settles a reload after a failed first load: new run %s`,
150 async (outcome) => {
151 const db = await getDatababase(getTestData(1))
152 const rxCollection: RxCollection<TestDocType> = db.test
153 const query = vi
154 .spyOn(rxCollection.storageInstance, `query`)
155 .mockRejectedValueOnce(new Error(`first query failed`))
156 if (outcome === `fail`)
157 query.mockRejectedValueOnce(new Error(`reload query failed`))
158 const collection = createCollection(
159 rxdbCollectionOptions({
160 rxCollection,
161 startSync: true,
162 syncBatchSize: 10,
163 }),
164 )
165 try {
166 await collection.preload().catch(() => undefined)
167 expect(collection.status).toBe(`error`)
168 const settled = await Promise.race([
169 collection.reload().then(
170 () => `resolved`,
171 () => `rejected`,
172 ),
173 new Promise((resolve) => setTimeout(() => resolve(`pending`), 500)),
174 ])
175 expect(settled).toBe(outcome === `ok` ? `resolved` : `rejected`)
176 expect(collection.status).toBe(outcome === `ok` ? `ready` : `error`)
177 if (outcome === `ok`) expect(collection.size).toBe(1)
178 else
179 expect(collection.health.error?.message).toBe(`reload query failed`)
180 } finally {
181 query.mockRestore()
182 await collection.cleanup()
183 await db.remove()
184 }
185 },
186 )
187
188 // The change stream is how the Collection learns of later writes. When it
189 // errors it ends, so the sync adapter has stopped: before the first ready
190 // the first load fails, and after it the rows stay and the node's `error`
191 // holds the cause until a reload.
192 it.each([`before`, `after`] as const)(
193 `fails when the change stream errors %s the first ready`,
194 async (when) => {
195 const db = await getDatababase(getTestData(1))
196 const rxCollection: RxCollection<TestDocType> = db.test
197 const changes = new Subject<never>()
198 const streamError = new Error(`RxDB change stream failed`)
199 const stream = vi
200 .spyOn(rxCollection, `$`, `get`)
201 .mockReturnValue(changes.asObservable() as never)
202 const releaseQuery = createDeferred<void>()
203 const storageQuery = rxCollection.storageInstance.query.bind(
204 rxCollection.storageInstance,
205 )
206 const query = vi
207 .spyOn(rxCollection.storageInstance, `query`)
208 .mockImplementationOnce(async (preparedQuery) => {
209 await releaseQuery.promise
210 return storageQuery(preparedQuery)
211 })
212 const collection = createCollection(
213 rxdbCollectionOptions({
214 rxCollection,
215 startSync: true,
216 syncBatchSize: 10,
217 }),
218 )
219 try {
220 if (when === `before`) {
221 const preload = collection.preload()
222 changes.error(streamError)
223 releaseQuery.resolve()
224 await expect(preload).rejects.toBe(streamError)
225 expect(collection.status).toBe(`error`)
226 } else {
227 releaseQuery.resolve()
228 await collection.preload()
229 changes.error(streamError)
230 expect(collection.status).toBe(`ready`)
231 expect(collection.size).toBe(1)
232 expect(collection.health.error?.message).toBe(streamError.message)
233 expect(collection.health.failureReason).toBeNull()
234 }
235 expect(OPEN_RXDB_SUBSCRIPTIONS.get(rxCollection)?.size ?? 0).toBe(0)
236 } finally {
237 releaseQuery.resolve()
238 query.mockRestore()
239 stream.mockRestore()
240 await collection.cleanup()
241 await db.remove()
242 }
243 },
244 )
245
246 // Receiving witness for the reload law (owner: the source-health oracle;
247 // maintainer decision F19): a reload keeps the rows on screen until it
248 // completes and then ends with the source's current rows. The first run
249 // listens to a change stream that never emits, so it misses an update, a
250 // delete, and an insert in RxDB and the Collection holds stale rows, one
251 // of them a row RxDB deleted. The reload's run listens to RxDB's own
252 // stream, and its initial fetch is held: until the fetch lands the stale
253 // rows stay; after it the rows equal RxDB's documents, so the deleted
254 // row is gone. The documents span two fetch batches.
255 it(`a reload of a ready Collection keeps its rows and ends with the documents`, async () => {
256 const db = await getDatababase(getTestData(12))
257 const rxCollection: RxCollection<TestDocType> = db.test
258 const silent = new Subject<never>()
259 const stream = vi
260 .spyOn(rxCollection, `$`, `get`)
261 .mockReturnValueOnce(silent.asObservable() as never)
262 const collection = createCollection(
263 rxdbCollectionOptions({
264 rxCollection,
265 startSync: true,
266 syncBatchSize: 10,
267 }),
268 )
269 const rows = () =>
270 new Map(collection.toArray.map((row) => [row.id, row.name]))
271 const documents = async () =>
272 new Map(
273 (await rxCollection.find().exec()).map((doc) => [doc.id, doc.name]),
274 )
275 const releaseFetch = createDeferred<void>()
276 const storageQuery = rxCollection.storageInstance.query.bind(
277 rxCollection.storageInstance,
278 )
279 let query: { mockRestore: () => void } | undefined
280 try {
281 await collection.preload()
282 // Only the first run listens to the silent stream.
283 stream.mockRestore()
284 await (await rxCollection.findOne(`1`).exec())!.incrementalPatch({
285 name: `edited`,
286 })
287 await (await rxCollection.findOne(`2`).exec())!.remove()
288 await rxCollection.insert({ id: `new`, name: `new` })
289 await flushPromises()
290 const stale = rows()
291 expect(stale.has(`2`)).toBe(true)
292 expect(stale).not.toEqual(await documents())
293
294 query = vi
295 .spyOn(rxCollection.storageInstance, `query`)
296 .mockImplementationOnce(async (preparedQuery) => {
297 await releaseFetch.promise
298 return storageQuery(preparedQuery)
299 })
300 let settled = false
301 const reload = collection.reload().then(() => (settled = true))
302 await flushPromises()
303 expect(rows(), `the rows stay until the fetch lands`).toEqual(stale)
304 expect(settled).toBe(false)
305
306 releaseFetch.resolve()
307 await Promise.race([
308 reload,
309 new Promise((resolve) => setTimeout(resolve, 500)),
310 ])
311 expect(settled).toBe(true)
312 expect(collection.status).toBe(`ready`)
313 expect(rows()).toEqual(await documents())
314 } finally {
315 releaseFetch.resolve()
316 query?.mockRestore()
317 stream.mockRestore()
318 await collection.cleanup()
319 await db.remove()
320 }
321 })
322
323 it(`marks initial sync ready only after its rows are applied`, async () => {
324 const db = await getDatababase([{ id: `server`, name: `Server` }])
325 const rxCollection: RxCollection<TestDocType> = db.test
326 const releaseInitialQuery = createDeferred<void>()
327 const initialQueryStarted = createDeferred<void>()
328 const storageQuery = rxCollection.storageInstance.query.bind(
329 rxCollection.storageInstance,
330 )
331 const query = vi
332 .spyOn(rxCollection.storageInstance, `query`)
333 .mockImplementationOnce(async (preparedQuery) => {
334 const result = await storageQuery(preparedQuery)
335 initialQueryStarted.resolve()
336 await releaseInitialQuery.promise
337 return result
338 })
339 const collection = createCollection(
340 rxdbCollectionOptions({
341 rxCollection,
342 startSync: true,
343 syncBatchSize: 10,
344 }),
345 )
346 const persistence = createDeferred<void>()
347 const transaction = createTransaction({
348 mutationFn: () => persistence.promise,
349 })
350
351 try {
352 await initialQueryStarted.promise
353 transaction.mutate(() =>
354 collection.insert({ id: `local`, name: `Local` }),
355 )
356 const buffered = await rxCollection.insert({
357 id: `buffered`,
358 name: `Buffered`,
359 })
360 releaseInitialQuery.resolve()
361
362 const ready = collection.preload()
363 await flushPromises()
364
365 // The initial receipt is still parked. A later live change for the
366 // same row must not overtake the older buffered insert.
367 await buffered.getLatest().patch({ name: `Newest` })
368 await flushPromises()
369
370 expect(collection.status).toBe(`loading`)
371 expect(collection.get(`server`)).toBeUndefined()
372 expect(collection.get(`buffered`)).toBeUndefined()
373
374 persistence.resolve()
375 await transaction.isPersisted.promise
376 await ready
377
378 expect(collection.get(`server`)).toEqual(
379 expect.objectContaining({ id: `server`, name: `Server` }),
380 )
381 expect(collection.get(`buffered`)).toEqual(
382 expect.objectContaining({ id: `buffered`, name: `Newest` }),
383 )
384 expect(collection.status).toBe(`ready`)
385 } finally {
386 releaseInitialQuery.resolve()
387 persistence.resolve()
388 await transaction.isPersisted.promise.catch(() => undefined)
389 query.mockRestore()
390 await collection.cleanup()
391 await db.remove()
392 }
393 })
394
395 it(`does not let later live traffic extend the startup readiness boundary`, async () => {
396 const db = await getDatababase()
397 const rxCollection: RxCollection<TestDocType> = db.test
398 const initialQueryStarted = createDeferred<void>()
399 const releaseInitialQuery = createDeferred<void>()
400 const bufferedApplied = createDeferred<void>()
401 const laterLiveApplied = createDeferred<void>()
402 const storageQuery = rxCollection.storageInstance.query.bind(
403 rxCollection.storageInstance,
404 )
405 const query = vi
406 .spyOn(rxCollection.storageInstance, `query`)
407 .mockImplementationOnce(async (preparedQuery) => {
408 const result = await storageQuery(preparedQuery)
409 initialQueryStarted.resolve()
410 await releaseInitialQuery.promise
411 return result
412 })
413 const options = rxdbCollectionOptions({ rxCollection })
414 const begin = vi.fn()
415 const write = vi.fn()
416 const commit = vi
417 .fn()
418 .mockReturnValueOnce(true)
419 .mockReturnValueOnce(bufferedApplied.promise)
420 .mockReturnValueOnce(laterLiveApplied.promise)
421 const markReady = vi.fn()
422 const fail = vi.fn()
423 const cleanup = options.sync.sync({
424 begin,
425 write,
426 commit,
427 markReady,
428 fail,
429 // A first load: the Collection holds no synced rows.
430 collection: {
431 status: `loading`,
432 _state: { acceptedSyncedEntries: () => new Map().entries() },
433 },
434 } as never)
435
436 try {
437 await initialQueryStarted.promise
438 await rxCollection.insert({ id: `buffered`, name: `Buffered` })
439 releaseInitialQuery.resolve()
440 await vi.waitFor(() => expect(commit).toHaveBeenCalledTimes(2))
441
442 await rxCollection.insert({ id: `later`, name: `Later` })
443 await vi.waitFor(() => expect(commit).toHaveBeenCalledTimes(3))
444 expect(markReady).not.toHaveBeenCalled()
445
446 bufferedApplied.resolve()
447 await vi.waitFor(() => expect(markReady).toHaveBeenCalledOnce())
448 } finally {
449 releaseInitialQuery.resolve()
450 bufferedApplied.resolve()
451 laterLiveApplied.resolve()
452 if (typeof cleanup === `function`) cleanup()
453 query.mockRestore()
454 await db.remove()
455 }
456 })
457
458 it(`should initialize and fetch initial data`, async () => {
459 const initialItems = getTestData(2)
460
461 const { collection, db } = await createTestState(initialItems)
462
463 // Verify the collection state contains our items
464 expect(collection.size).toBe(initialItems.length)
465 expect(stripVirtualProps(collection.get(`1`))).toEqual(initialItems[0])
466 expect(stripVirtualProps(collection.get(`2`))).toEqual(initialItems[1])
467
468 // Verify the synced data
469 expect(collection._state.syncedData.size).toBe(initialItems.length)
470 expect(collection._state.syncedData.get(`1`)).toEqual(initialItems[0])
471 expect(collection._state.syncedData.get(`2`)).toEqual(initialItems[1])
472
473 await db.remove()
474 })
475
476 it(`should initialize and fetch initial data with many documents`, async () => {
477 const docsAmount = 25 // > 10 to force multiple batches
478 const initialItems = getTestData(docsAmount)
479 const { collection, db } = await createTestState(initialItems)
480
481 // All docs should be present after initial sync
482 expect(collection.size).toBe(docsAmount)
483 expect(collection._state.syncedData.size).toBe(docsAmount)
484
485 // Spot-check a few positions
486 expect(stripVirtualProps(collection.get(`1`))).toEqual({
487 id: `1`,
488 name: `Item 1`,
489 })
490 expect(stripVirtualProps(collection.get(`10`))).toEqual({
491 id: `10`,
492 name: `Item 10`,
493 })
494 expect(stripVirtualProps(collection.get(`11`))).toEqual({
495 id: `11`,
496 name: `Item 11`,
497 })
498 expect(stripVirtualProps(collection.get(`25`))).toEqual({
499 id: `25`,
500 name: `Item 25`,
501 })
502
503 // Ensure no gaps
504 for (let i = 1; i <= docsAmount; i++) {
505 expect(collection.has(String(i))).toBe(true)
506 }
507
508 await db.remove()
509 })
510
511 it(`should update the collection when RxDB changes data`, async () => {
512 const initialItems = getTestData(2)
513
514 const { collection, rxCollection, db } =
515 await createTestState(initialItems)
516
517 // inserts
518 const doc = await rxCollection.insert({ id: `3`, name: `inserted` })
519 expect(stripVirtualProps(collection.get(`3`))?.name).toEqual(`inserted`)
520
521 // updates
522 await doc.getLatest().patch({ name: `updated` })
523 expect(stripVirtualProps(collection.get(`3`))?.name).toEqual(`updated`)
524
525 // deletes
526 await doc.getLatest().remove()
527 expect(stripVirtualProps(collection.get(`3`))).toEqual(undefined)
528
529 await db.remove()
530 })
531
532 it(`should update RxDB when the collection changes data`, async () => {
533 const initialItems = getTestData(2)
534
535 const { collection, rxCollection, db } =
536 await createTestState(initialItems)
537
538 // inserts
539 const tx = collection.insert({ id: `3`, name: `inserted` })
540 await tx.isPersisted.promise
541 let doc = await rxCollection.findOne(`3`).exec(true)
542 expect(doc.name).toEqual(`inserted`)
543
544 // updates
545 collection.update(`3`, (d) => {
546 d.name = `updated`
547 })
548 expect(stripVirtualProps(collection.get(`3`))?.name).toEqual(`updated`)
549 await collection.stateWhenReady()
550 await rxCollection.database.requestIdlePromise()
551 doc = await rxCollection.findOne(`3`).exec(true)
552 expect(doc.name).toEqual(`updated`)
553
554 // deletes
555 collection.delete(`3`)
556 await rxCollection.database.requestIdlePromise()
557 const mustNotBeFound = await rxCollection.findOne(`3`).exec()
558 expect(mustNotBeFound).toEqual(null)
559
560 await db.remove()
561 })
562 })
563
564 describe(`lifecycle management`, () => {
565 it(`should call unsubscribe when collection is cleaned up`, async () => {
566 const { collection, rxCollection, db } = await createTestState()
567
568 await collection.cleanup()
569
570 const subs = getFromMapOrCreate(
571 OPEN_RXDB_SUBSCRIPTIONS,
572 rxCollection,
573 () => new Set(),
574 )
575 expect(subs.size).toEqual(0)
576
577 await db.remove()
578 })
579
580 it(`should restart sync when collection is accessed after cleanup`, async () => {
581 const initialItems = getTestData(2)
582 const { collection, rxCollection, db } =
583 await createTestState(initialItems)
584
585 await collection.cleanup()
586 await flushPromises()
587 expect(collection.status).toBe(`cleaned-up`)
588
589 // insert into RxDB while cleaned-up
590 await rxCollection.insert({ id: `3`, name: `Item 3` })
591
592 // Access collection data to restart sync
593 const subscription = collection.subscribeChanges(() => {})
594
595 await collection.toArrayWhenReady()
596 expect(stripVirtualProps(collection.get(`3`))?.name).toEqual(`Item 3`)
597
598 subscription.unsubscribe()
599 await db.remove()
600 })
601 })
602
603 /**
604 * Here we simulate having multiple browser tabs
605 * open where the data should still be in sync.
606 */
607 describe(`multi tab`, () => {
608 it(`should update the state accross instances`, async () => {
609 const dbid = dbNameId++
610 const db1 = await getDatababase([], dbid)
611 const db2 = await getDatababase(getTestData(2), dbid)
612
613 const col1 = createCollection(
614 rxdbCollectionOptions({
615 rxCollection: db1.test,
616 startSync: true,
617 }),
618 )
619 const col2 = createCollection(
620 rxdbCollectionOptions({
621 rxCollection: db2.test,
622 startSync: true,
623 }),
624 )
625 await col1.stateWhenReady()
626 await col2.stateWhenReady()
627
628 // tanstack-db writes
629 col1.insert({ id: `t1`, name: `t1` })
630 col2.insert({ id: `t2`, name: `t2` })
631 await db1.test.findOne(`t1`).exec(true)
632 await db1.test.findOne(`t2`).exec(true)
633 await db2.test.findOne(`t1`).exec(true)
634 await db2.test.findOne(`t2`).exec(true)
635 expect(col2.get(`t1`)).toBeTruthy()
636 expect(col1.get(`t2`)).toBeTruthy()
637
638 // RxDB writes
639 await db1.test.insert({ id: `rx1`, name: `rx1` })
640 await db2.test.insert({ id: `rx2`, name: `rx2` })
641 expect(col2.get(`rx1`)).toBeTruthy()
642 expect(col1.get(`rx2`)).toBeTruthy()
643
644 db1.remove()
645 db2.remove()
646 })
647 })
648
649 describe(`error handling`, () => {
650 function expectAdditionalPropertyError(error: unknown, id: string) {
651 expect(error).toBeInstanceOf(Error)
652 expect(error).toHaveProperty(
653 `message`,
654 expect.stringMatching(/schema validation error/),
655 )
656 expect(error).toMatchObject({
657 code: `COL20`,
658 rxdb: true,
659 parameters: {
660 document: id,
661 writeError: {
662 status: 422,
663 documentId: id,
664 validationErrors: expect.arrayContaining([
665 expect.objectContaining({
666 keyword: `additionalProperties`,
667 params: { additionalProperty: `foo` },
668 }),
669 ]),
670 },
671 },
672 })
673 }
674
675 it(`rejects an extra field at the provider and accepts its valid neighbor`, async () => {
676 const db = await getDatababase()
677 try {
678 const invalid = { id: `3`, name: `invalid`, foo: `bar` }
679 const rejected = await db.test.bulkUpsert([invalid])
680 expect(rejected.success).toEqual([])
681 expect(rejected.error).toHaveLength(1)
682 expect(rejected.error[0]).toMatchObject({
683 status: 422,
684 documentId: `3`,
685 validationErrors: expect.arrayContaining([
686 expect.objectContaining({
687 keyword: `additionalProperties`,
688 params: { additionalProperty: `foo` },
689 }),
690 ]),
691 })
692 expect(await db.test.find().exec()).toEqual([])
693
694 const accepted = await db.test.bulkUpsert([
695 { id: `3`, name: `invalid` },
696 ])
697 expect(accepted.error).toEqual([])
698 expect(accepted.success).toHaveLength(1)
699 const rows = await db.test.find().exec()
700 expect(rows.map((row) => ({ id: row.id, name: row.name }))).toEqual([
701 { id: `3`, name: `invalid` },
702 ])
703 expect(rows[0]!.toJSON()).not.toHaveProperty(`foo`)
704 } finally {
705 await db.remove()
706 }
707 })
708
709 it(`should rollback the transaction on invalid data that does not match the RxCollection schema`, async () => {
710 const initialItems = getTestData(2)
711 const { collection, rxCollection, db } =
712 await createTestState(initialItems)
713 const outcomes: Array<Promise<unknown>> = []
714 const observe = (promise: Promise<unknown>) => {
715 const outcome = promise.then(
716 () => ({ status: `fulfilled` as const }),
717 (error: unknown) => ({ status: `rejected` as const, error }),
718 )
719 outcomes.push(outcome)
720 return outcome
721 }
722 const expectRows = async (expected: Array<TestDocType>) => {
723 expect(collection.toArray.map((row) => stripVirtualProps(row))).toEqual(
724 expected,
725 )
726 const stored = await rxCollection.find().exec()
727 expect(stored.map((row) => ({ id: row.id, name: row.name }))).toEqual(
728 expected,
729 )
730 for (const row of stored) {
731 expect(row.toJSON()).not.toHaveProperty(`foo`)
732 }
733 }
734
735 try {
736 // Both old invalid inputs reach the actual provider through persistence.
737 const invalid = { id: `3`, name: `invalid`, foo: `bar` }
738 const insert = collection.insert(invalid)
739 const inserted = observe(insert.isPersisted.promise)
740 expect(collection.has(`3`)).toBe(true)
741 const insertOutcome = await inserted
742 expect(insertOutcome.status).toBe(`rejected`)
743 if (insertOutcome.status !== `rejected`) {
744 throw new Error(`Invalid insert unexpectedly persisted`)
745 }
746 expectAdditionalPropertyError(insertOutcome.error, `3`)
747 expect(collection.has(`3`)).toBe(false)
748 await expectRows(initialItems)
749
750 const update = collection.update(`2`, (draft) => {
751 Object.assign(draft, { name: `invalid`, foo: `bar` })
752 })
753 const updated = observe(update.isPersisted.promise)
754 expect(collection.get(`2`)?.name).toBe(`invalid`)
755 const updateOutcome = await updated
756 expect(updateOutcome.status).toBe(`rejected`)
757 if (updateOutcome.status !== `rejected`) {
758 throw new Error(`Invalid update unexpectedly persisted`)
759 }
760 expectAdditionalPropertyError(updateOutcome.error, `2`)
761 expect(stripVirtualProps(collection.get(`2`))?.name).toBe(`Item 2`)
762 await expectRows(initialItems)
763
764 const next = collection.update(`2`, (draft) => {
765 draft.name = `Valid`
766 })
767 expect(await observe(next.isPersisted.promise)).toEqual({
768 status: `fulfilled`,
769 })
770 await expectRows([
771 { id: `1`, name: `Item 1` },
772 { id: `2`, name: `Valid` },
773 ])
774 } finally {
775 await Promise.all(outcomes)
776 await collection.cleanup()
777 await db.remove()
778 }
779 })
780 })
781})