Open History to see the last commit
1import { createCollection, createTransaction } from '@tanstack/db'
2import { expect, it, vi } from 'vitest'
3import { PowerSyncTransactor } from '../src/PowerSyncTransactor'
4import type { CommonPowerSyncDatabase } from '@powersync/common'
5
6it.each([`cleanup`, `error`, `ready`] as const)(
7 `settles a transaction waiting for source readiness on %s`,
8 async (outcome) => {
9 const writeTransaction = vi
10 .fn()
11 .mockResolvedValue({ whenComplete: Promise.resolve() })
12 // This boundary must settle before taking a database lock; no SQL runs.
13 const transactor = new PowerSyncTransactor({
14 database: { writeTransaction } as unknown as CommonPowerSyncDatabase,
15 })
16 let markSourceReady!: () => void
17 const collection = createCollection<{ id: string }>({
18 getKey: (row) => row.id,
19 sync: {
20 sync: ({ markReady }) => {
21 markSourceReady = markReady
22 return {}
23 },
24 },
25 })
26 collection.startSyncImmediate()
27 const transaction = createTransaction({
28 autoCommit: false,
29 mutationFn: async () => {},
30 })
31 transaction.mutate(() => collection.insert({ id: `pending` }))
32 let result: { error: unknown } | { ready: true } | undefined
33 const waiting = transactor.applyTransaction(transaction).then(
34 () => {
35 result = { ready: true }
36 },
37 (error: unknown) => {
38 result = { error }
39 },
40 )
41 const failure = new Error(`source failed before readiness`)
42 try {
43 expect(collection.status).toBe(`loading`)
44 if (outcome === `cleanup`) await collection.cleanup()
45 else if (outcome === `error`) collection._lifecycle.fail(failure)
46 else markSourceReady()
47 // Drain promise reactions without waiting on the possibly orphaned wait.
48 for (let turn = 0; turn < 10; turn++) await Promise.resolve()
49 expect(result).toBeDefined()
50 expect(result).toEqual(
51 outcome === `ready`
52 ? { ready: true }
53 : {
54 error:
55 outcome === `error`
56 ? failure
57 : expect.objectContaining({ name: `AbortError` }),
58 },
59 )
60 await waiting
61 expect(writeTransaction).toHaveBeenCalledTimes(
62 outcome === `ready` ? 1 : 0,
63 )
64 } finally {
65 transaction.rollback()
66 await collection.cleanup()
67 }
68 },
69)