Skip to content
clientdb

Search the docs

Find a page or section

Guides

Testing

Test client code against an in-memory server with createTestClient, and permissions end to end with testEngine on a real Postgres.

The examples test the todo app from the quick start, with Vitest.

Client code: createTestClient

createTestClient from @clientdb/client/testing gives you a real database client wired to an in-memory server: it applies transactions in arrival order, assigns revisions, cascades deletes along onDelete: "cascade" relations and broadcasts full rows to every connected client, with no permissions. The client starts with the seeded rows.

test/todos.test.ts
import { createTestClient } from "@clientdb/client/testing";
import { expect, test } from "vitest";
import { schema } from "../src/sync/schema";

test("renaming a todo", async () => {
  const { db } = createTestClient(schema, {
    seed: {
      user: [{ id: "alice", name: "Alice", email: "alice@example.com" }],
      project: [{ id: "launch", name: "Launch" }],
    },
    viewer: { model: "user", id: "alice" },
  });

  const todo = db.todo.create({ projectId: "launch", authorId: db.$session.viewerId!, title: "New" });
  await todo.update({ title: "Renamed" }).confirmed;
  expect(db.todo.get(todo.id)?.title).toBe("Renamed");
});

Options:

  • viewer: the signed-in viewer, as a server would report it, for db.$session and db.$viewer. null is an anonymous, read-only session.
  • latencyMs: a simulated network delay each way (demos).
  • online: false and setOnline(next): offline periods; writes and server packets wait until the client is back online.
  • server: share one server between clients, e.g. two devices of the same user.
  • mode: "manual": hold server packets until server.deliver(), to test optimistic state and rebase.
  • Every option of createDatabaseClient except the transport, such as readOnly or models.

The server (LoopbackServer) can also refuse writes, to test rollbacks and onTransactionError: new LoopbackServer(schema, { validate: (transaction, server) => { … } }), passed as server. server.serverWrite(operation) simulates someone else's write.

Permissions and sync: testEngine

testEngine from @clientdb/server/testing runs a real engine on a real Postgres database, with no HTTP in between, to test what each user receives. It migrates and starts the engine and gives the test a tenant of its own, so tests can share one database. Its writes and connect() resolve once connected clients received the result, so tests never wait by hand.

test/permissions.test.ts
import { testEngine } from "@clientdb/server/testing";
import { expect, test } from "vitest";
import { permissions } from "../src/sync/permissions";

test("admins see private todos", async () => {
  const testing = await testEngine({ permissions, database: process.env.TEST_DATABASE_URL! });

  // typed writes without permission checks
  await testing.system.user.create({ id: "alice", name: "Alice", email: "alice@example.com" });
  await testing.system.user.create({ id: "bob", name: "Bob", email: "bob@example.com" });
  await testing.system.project.create({ id: "launch", name: "Launch" });
  await testing.system.member.create({ id: "alice-launch", projectId: "launch", userId: "alice", role: "admin" });
  await testing.system.member.create({ id: "bob-launch", projectId: "launch", userId: "bob", role: "member" });
  await testing.system.todo.create({ projectId: "launch", authorId: "alice", title: "Shared" });
  await testing.system.todo.create({ projectId: "launch", authorId: "alice", title: "Alice's notes", isPrivate: true });

  const bob = await testing.connect("bob");
  expect(bob.db.todo.all.map((todo) => todo.title)).toEqual(["Shared"]);

  await testing.system.member.update("bob-launch", { role: "admin" });
  expect(bob.db.todo.count).toBe(2); // the private todo moved in

  bob.disconnect(); // goes offline, keeps local state
  await bob.reconnect(); // catches up from the last sync id

  await testing.close();
});

system writes only the schema's fields, so a column omitted from it (here passwordHash) needs a default in schema.prisma, or the row must be created with Prisma.

The session can carry everything a real session() callback returns:

  • testing.connect("bob", { readOnly: true }): a read-only session; its writes are refused with ReadOnly.
  • testing.connect("bob", { claims: [$staff()] }): a session with claims.
  • await bob.setSession({ claims: [] }): changes the claims or the read-only flag of a connected client, as a live server does when it checks the session again. Rows the session can no longer read leave bob.db.
  • testing.connect(null): an anonymous visitor.

connectClient(engine, { viewer, tenant, claims, readOnly, load, eviction }) from @clientdb/server/testing (also exported by @clientdb/server) is the lower-level piece testEngine uses: a client on an engine you set up yourself. load: "lazy" and eviction test a client that loads every model when read, as an admin panel would.

Checking rules without a database

compileAccess(permissions).explain() prints the compiled plan; a rule that can't be routed throws AccessCompileError when the engine or plan is created, so a unit test that just builds the plan catches it in CI.

test/rules.test.ts
import { compileAccess } from "@clientdb/server";
import { expect, test } from "vitest";
import { permissions } from "../src/sync/permissions";

test("permissions compile", () => {
  expect(() => {
    return compileAccess(permissions);
  }).not.toThrow();
});