# Test offline sync

https://docs.serverpod.dev/next/concepts/data-and-the-database/database/offline-sync/testing

The [`withServerpod`](https://docs.serverpod.dev/next/concepts/testing/get-started.md) test helper starts a test server without offline sync, which your real server gets from its generated code. Turn offline sync on in each test group that uses synced tables.

## Turn on offline sync in a test group

Turn off rollbacks, pass the offline sync [database interceptor](https://docs.serverpod.dev/next/concepts/data-and-the-database/database/database-interceptors.md) to `withServerpod`, and initialize offline sync on the test server:

```dart
import 'package:my_project_server/src/generated/protocol.dart';
import 'package:serverpod/serverpod.dart';
import 'package:serverpod_offline_sync_server/serverpod_offline_sync_server.dart';
import 'package:test/test.dart';

import 'test_tools/serverpod_test_tools.dart';

void main() {
  withServerpod(
    'Given synced tasks',
    rollbackDatabase: RollbackDatabase.disabled,
    databaseInterceptor: offlineSyncDatabaseInterceptor,
    (sessionBuilder, endpoints) {
      setUpAll(() {
        sessionBuilder
            .build()
            .serverpod
            .initializeOfflineSync(syncTables: syncTables);
      });

      test('when a user adds a task, then they can read it', () async {
        final session = sessionBuilder.build();
        final userId = const Uuid().v7obj();
        final tasks = await session.db.transactionForUser(
          userId,
          (transaction) async {
            await Task.db.insertRow(
              session,
              Task(title: 'Buy milk'),
              transaction: transaction,
            );
            return Task.db.find(session, transaction: transaction);
          },
        );
        expect(tasks.map((task) => task.title), ['Buy milk']);
      });
    },
  );
}
```

Two details make this setup work:

- **Initialize before you create sessions.** The interceptor only adds offline sync to sessions created after `initializeOfflineSync` runs.
- **Turn off rollbacks, and give each test its own user.** The test's [rollback](https://docs.serverpod.dev/next/concepts/testing/configuration.md#rollbackdatabase) doesn't undo writes inside `transactionForUser`. On SQLite, those writes also hang until the test times out. Reads inside `transactionForUser` return only rows from that user's spaces.

:::note
If your server also has its own database interceptor, call it inside offline sync's interceptor, as the generated server does:

```dart
databaseInterceptor: (session, inner) =>
    offlineSyncDatabaseInterceptor(session, yourInterceptor(session, inner)),
```

:::

## Test endpoints that use synced tables

In a group set up this way, call endpoints that use synced tables through the generated test tools, as you would any endpoint. The endpoint takes the user id from `session.authenticated`, so give the call a [signed-in user](https://docs.serverpod.dev/next/concepts/testing/writing-tests.md#simulate-authentication):

```dart
final userId = const Uuid().v7obj();
final tasks = await endpoints.task.myTasks(
  sessionBuilder.copyWith(
    authentication: AuthenticationOverride.authenticationInfo(
      userId.uuid,
      {},
    ),
  ),
);
```

## Test the device side

Code that runs on the device needs no server to test. Open a sync session on a temporary file with the generated client, then test your local reads and writes:

```dart
final userId = const Uuid().v7obj();
final session = await Client('http://localhost:8080/').createSyncSession(
  p.join(Directory.systemTemp.path, 'test_$userId.db'),
  persistentUserId: userId,
);
```

Close the session in `tearDown`, and delete the file along with its `-wal` and `-shm` files.

## Related

- [Testing configuration](https://docs.serverpod.dev/next/concepts/testing/configuration.md): every `withServerpod` option, including rollbacks.
- [Share data with spaces](https://docs.serverpod.dev/next/concepts/data-and-the-database/database/offline-sync/spaces.md): the server code these tests cover.
