Skip to content

Commit 11b7a36

Browse files
Update more tests to use mocked sync service
1 parent 28472e3 commit 11b7a36

File tree

2 files changed

+65
-45
lines changed

2 files changed

+65
-45
lines changed

packages/web/tests/multiple_instances.test.ts

Lines changed: 56 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { beforeAll, describe, expect, it, onTestFinished, vi } from 'vitest';
55
import { LockedAsyncDatabaseAdapter } from '../src/db/adapters/LockedAsyncDatabaseAdapter';
66
import { WebDBAdapter } from '../src/db/adapters/WebDBAdapter';
77
import { WorkerWrappedAsyncDatabaseConnection } from '../src/db/adapters/WorkerWrappedAsyncDatabaseConnection';
8+
import { getMockSyncServiceFromWorker } from './utils/MockSyncService';
89
import { createTestConnector, sharedMockSyncServiceTest } from './utils/mockSyncServiceTest';
910
import { generateTestDb, testSchema } from './utils/testDb';
1011

@@ -37,45 +38,58 @@ describe('Multiple Instances', { sequential: true }, () => {
3738
expect(assets.length).equals(1);
3839
});
3940

40-
it('should broadcast logs from shared sync worker', { timeout: 20000 }, async () => {
41-
const logger = createLogger('test-logger');
42-
const spiedErrorLogger = vi.spyOn(logger, 'error');
43-
const spiedDebugLogger = vi.spyOn(logger, 'debug');
41+
sharedMockSyncServiceTest(
42+
'should broadcast logs from shared sync worker',
43+
{ timeout: 10_000 },
44+
async ({ context: { database, connect, openDatabase } }) => {
45+
const logger = createLogger('test-logger');
46+
const spiedErrorLogger = vi.spyOn(logger, 'error');
47+
const spiedDebugLogger = vi.spyOn(logger, 'debug');
48+
49+
// Open an additional database which we can spy on the logs.
50+
const powersync = openDatabase({
51+
logger
52+
});
4453

45-
const powersync = generateTestDb({
46-
logger,
47-
database: {
48-
dbFilename: 'broadcast-logger-test.sqlite'
49-
},
50-
schema: testSchema
51-
});
54+
powersync.connect({
55+
fetchCredentials: async () => {
56+
return {
57+
endpoint: 'http://localhost/does-not-exist',
58+
token: 'none'
59+
};
60+
},
61+
uploadData: async (db) => {}
62+
});
5263

53-
powersync.connect({
54-
fetchCredentials: async () => {
55-
return {
56-
endpoint: 'http://localhost/does-not-exist',
57-
token: 'none'
58-
};
59-
},
60-
uploadData: async (db) => {}
61-
});
64+
// Should log that a connection attempt has been made
65+
const message = 'Streaming sync iteration started';
66+
await vi.waitFor(
67+
() =>
68+
expect(
69+
spiedDebugLogger.mock.calls
70+
.flat(1)
71+
.find((argument) => typeof argument == 'string' && argument.includes(message))
72+
).exist,
73+
{ timeout: 2000 }
74+
);
6275

63-
// Should log that a connection attempt has been made
64-
const message = 'Streaming sync iteration started';
65-
await vi.waitFor(
66-
() =>
67-
expect(
68-
spiedDebugLogger.mock.calls
69-
.flat(1)
70-
.find((argument) => typeof argument == 'string' && argument.includes(message))
71-
).exist,
72-
{ timeout: 2000 }
73-
);
74-
75-
// The connection should fail with an error
76-
await vi.waitFor(() => expect(spiedErrorLogger.mock.calls.length).gt(0), { timeout: 2000 });
77-
// This test seems to take quite long while waiting for this disconnect call
78-
});
76+
await vi.waitFor(async () => {
77+
const syncService = await getMockSyncServiceFromWorker(powersync.database.name);
78+
if (!syncService) {
79+
throw new Error('Sync service not found');
80+
}
81+
const requests = await syncService.getPendingRequests();
82+
expect(requests.length).toBeGreaterThan(0);
83+
const pendingRequestId = requests[0].id;
84+
// Generate an error
85+
await syncService.createResponse(pendingRequestId, 401, { 'Content-Type': 'application/json' });
86+
await syncService.completeResponse(pendingRequestId);
87+
});
88+
89+
// The connection should fail with an error
90+
await vi.waitFor(() => expect(spiedErrorLogger.mock.calls.length).gt(0), { timeout: 2000 });
91+
}
92+
);
7993

8094
it('should maintain DB connections if instances call close', async () => {
8195
/**
@@ -215,11 +229,14 @@ describe('Multiple Instances', { sequential: true }, () => {
215229

216230
expect(database.currentStatus.connected).false;
217231
expect(secondDatabase.currentStatus.connected).false;
218-
// connect the first database
219-
await connect();
232+
// connect the second database in order for it to have access to the sync service.
233+
secondDatabase.connect(createTestConnector());
234+
// connect the first database - this will actually connect to the sync service.
235+
const { syncService } = await connect();
220236

221237
expect(database.currentStatus.connected).true;
222-
expect(secondDatabase.currentStatus.connected).true;
238+
239+
await vi.waitFor(() => expect(secondDatabase.currentStatus.connected).true);
223240
});
224241

225242
sharedMockSyncServiceTest(

packages/web/tests/utils/mockSyncServiceTest.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
column,
99
createBaseLogger
1010
} from '@powersync/common';
11-
import { PowerSyncDatabase } from '@powersync/web';
11+
import { PowerSyncDatabase, WebPowerSyncDatabaseOptions } from '@powersync/web';
1212
import { MockedFunction, expect, onTestFinished, test, vi } from 'vitest';
1313
import { MockSyncService, getMockSyncServiceFromWorker } from './MockSyncServiceClient';
1414

@@ -62,7 +62,7 @@ export const sharedMockSyncServiceTest = test.extend<{
6262
connect: (customConnector?: PowerSyncBackendConnector) => Promise<ConnectResult>;
6363
database: PowerSyncDatabase;
6464
databaseName: string;
65-
openDatabase: () => PowerSyncDatabase;
65+
openDatabase: (customConfig?: Partial<WebPowerSyncDatabaseOptions>) => PowerSyncDatabase;
6666
};
6767
}>({
6868
context: async ({}, use) => {
@@ -71,18 +71,21 @@ export const sharedMockSyncServiceTest = test.extend<{
7171
logger.setLevel(LogLevel.DEBUG);
7272
logger.useDefaults();
7373

74-
const openDatabase = () => {
74+
const openDatabase = (customConfig: Partial<WebPowerSyncDatabaseOptions> = {}) => {
7575
const db = new PowerSyncDatabase({
7676
database: {
77-
dbFilename
77+
dbFilename,
78+
...(customConfig.database ?? {})
7879
},
7980
flags: {
80-
enableMultiTabs: true
81+
enableMultiTabs: true,
82+
...(customConfig.flags ?? {})
8183
},
8284
retryDelayMs: 1000,
8385
crudUploadThrottleMs: 1000,
8486
schema: AppSchema,
85-
logger
87+
logger,
88+
...customConfig
8689
});
8790
onTestFinished(async () => {
8891
if (!db.closed) {

0 commit comments

Comments
 (0)