Triplit Testing Guide: Real-Time DB, Access Control, and Schema Validation
Triplit is a full-stack real-time database with TypeScript-first schema definition, built-in access control, and automatic client-server sync. Unlike most local-first frameworks, Triplit stores data locally in an IndexedDB-backed store and syncs with a Triplit server — giving you SQL-like queries with real-time updates.
Testing Triplit applications means verifying schema correctness, access control enforcement, query behavior, and sync semantics.
Triplit's Testing Architecture
Triplit has four testable layers:
- Schema — TypeScript-defined, validates at compile time and runtime
- Queries — relational, supports filtering, ordering, pagination, and includes
- Access control — server-side rules enforce who can read/write what
- Sync — bidirectional, real-time, with conflict resolution
Setting Up the Test Environment
npm install @triplit/client @triplit/db vitestTriplit provides an in-memory client for testing:
// test-utils.ts
import { TriplitClient, Schema as S } from "@triplit/client";
import { MemoryStorage } from "@triplit/db";
// Define your app's schema
const schema = {
todos: {
schema: S.Schema({
id: S.Id(),
title: S.String(),
completed: S.Boolean({ default: false }),
priority: S.Number({ default: 0 }),
tags: S.Set(S.String()),
ownerId: S.String(),
listId: S.Optional(S.String()),
createdAt: S.Date({ default: S.Default.now() }),
}),
},
lists: {
schema: S.Schema({
id: S.Id(),
name: S.String(),
ownerId: S.String(),
createdAt: S.Date({ default: S.Default.now() }),
}),
},
};
type Schema = typeof schema;
export function createTestClient(userId: string = "test-user-1") {
return new TriplitClient<Schema>({
schema,
storage: new MemoryStorage(),
// No server URL — in-memory only for unit tests
autoConnect: false,
token: createTestToken(userId),
});
}
function createTestToken(userId: string) {
// Test JWT with user claims (in production, this comes from your auth provider)
return `test.${btoa(JSON.stringify({ sub: userId, "x-triplit-token-type": "external" }))}.sig`;
}
export async function seedClient(
client: TriplitClient<Schema>,
data: {
todos?: Array<Partial<{ id: string; title: string; completed: boolean; ownerId: string; listId?: string; priority?: number; tags?: string[] }>>;
lists?: Array<Partial<{ id: string; name: string; ownerId: string }>>;
}
) {
for (const todo of data.todos ?? []) {
await client.insert("todos", {
id: todo.id ?? crypto.randomUUID(),
title: todo.title ?? "Default todo",
completed: todo.completed ?? false,
priority: todo.priority ?? 0,
tags: new Set(todo.tags ?? []),
ownerId: todo.ownerId ?? "test-user-1",
...(todo.listId && { listId: todo.listId }),
});
}
for (const list of data.lists ?? []) {
await client.insert("lists", {
id: list.id ?? crypto.randomUUID(),
name: list.name ?? "Default list",
ownerId: list.ownerId ?? "test-user-1",
});
}
}Testing Schema Validation
Triplit's schema is the contract for your data — test it explicitly:
import { describe, test, expect } from "vitest";
describe("Triplit Schema Validation", () => {
test("schema defines required collections", () => {
const collectionNames = Object.keys(schema);
expect(collectionNames).toContain("todos");
expect(collectionNames).toContain("lists");
});
test("todos schema has required fields", () => {
const todoProps = Object.keys(schema.todos.schema.properties);
const requiredFields = ["id", "title", "completed", "ownerId"];
for (const field of requiredFields) {
expect(todoProps).toContain(field);
}
});
test("completed defaults to false", () => {
const completedProp = schema.todos.schema.properties.completed;
expect(completedProp.type).toBe("boolean");
expect(completedProp.options?.default).toBe(false);
});
test("tags is a Set type", () => {
const tagsProp = schema.todos.schema.properties.tags;
expect(tagsProp.type).toBe("set");
});
test("insert validates required fields", async () => {
const client = createTestClient();
// Missing required 'title' field
await expect(
client.insert("todos", {
id: "invalid-1",
// title is missing
completed: false,
ownerId: "user-1",
priority: 0,
tags: new Set(),
} as any)
).rejects.toThrow();
await client.disconnect();
});
test("optional fields can be omitted", async () => {
const client = createTestClient();
// listId is optional
const result = await client.insert("todos", {
id: "no-list",
title: "No list todo",
completed: false,
priority: 0,
tags: new Set(),
ownerId: "user-1",
// listId omitted
});
expect(result.output?.id).toBe("no-list");
await client.disconnect();
});
});Testing Queries
Triplit's query API is expressive and type-safe:
describe("Triplit Queries", () => {
let client: TriplitClient<Schema>;
beforeEach(async () => {
client = createTestClient();
await seedClient(client, {
lists: [
{ id: "list-1", name: "Personal", ownerId: "test-user-1" },
{ id: "list-2", name: "Work", ownerId: "test-user-1" },
],
todos: [
{ id: "t1", title: "Buy groceries", completed: false, ownerId: "test-user-1", listId: "list-1", priority: 1 },
{ id: "t2", title: "Read book", completed: true, ownerId: "test-user-1", listId: "list-1", priority: 2 },
{ id: "t3", title: "Write report", completed: false, ownerId: "test-user-1", listId: "list-2", priority: 3 },
{ id: "t4", title: "Other user", completed: false, ownerId: "user-2", listId: "list-2", priority: 0 },
]
});
});
afterEach(async () => { await client.disconnect(); });
test("fetch all todos for owner", async () => {
const result = await client.fetch(
client.query("todos").where("ownerId", "=", "test-user-1").build()
);
expect(result.size).toBe(3);
});
test("filter by completed status", async () => {
const result = await client.fetch(
client.query("todos")
.where("ownerId", "=", "test-user-1")
.where("completed", "=", true)
.build()
);
expect(result.size).toBe(1);
expect([...result.values()][0].title).toBe("Read book");
});
test("order by priority descending", async () => {
const result = await client.fetch(
client.query("todos")
.where("ownerId", "=", "test-user-1")
.order("priority", "DESC")
.build()
);
const todos = [...result.values()];
expect(todos[0].priority).toBe(3);
expect(todos[todos.length - 1].priority).toBe(1);
});
test("limit returns correct number", async () => {
const result = await client.fetch(
client.query("todos")
.where("ownerId", "=", "test-user-1")
.limit(2)
.build()
);
expect(result.size).toBe(2);
});
test("filter by listId", async () => {
const result = await client.fetch(
client.query("todos")
.where("listId", "=", "list-1")
.build()
);
expect(result.size).toBe(2);
const titles = [...result.values()].map(t => t.title);
expect(titles).toContain("Buy groceries");
expect(titles).toContain("Read book");
});
test("Set membership filter (tags)", async () => {
// Add a todo with tags first
await client.insert("todos", {
id: "tagged-1",
title: "Tagged todo",
completed: false,
priority: 0,
tags: new Set(["urgent", "important"]),
ownerId: "test-user-1",
});
const result = await client.fetch(
client.query("todos")
.where("tags", "has", "urgent")
.build()
);
expect(result.size).toBeGreaterThan(0);
const taggedTodo = [...result.values()].find(t => t.id === "tagged-1");
expect(taggedTodo).toBeDefined();
});
test("include related collection (join-like)", async () => {
// Triplit doesn't have SQL JOINs but supports include for related data
const result = await client.fetch(
client.query("lists")
.where("ownerId", "=", "test-user-1")
.include("todos", (rel) =>
rel.query("todos")
.where("listId", "=", "$id")
.build()
)
.build()
);
const lists = [...result.values()];
expect(lists).toHaveLength(2);
const personalList = lists.find(l => l.name === "Personal");
expect(personalList?.todos).toBeDefined();
});
});Testing Access Control
Triplit's access control is defined in your schema and enforced by the server:
// Schema with access control
const schemaWithAcl = {
todos: {
schema: S.Schema({
id: S.Id(),
title: S.String(),
completed: S.Boolean({ default: false }),
ownerId: S.String(),
}),
permissions: {
read: {
filter: [["ownerId", "=", "$SESSION_USER_ID"]],
},
insert: {
filter: [["ownerId", "=", "$SESSION_USER_ID"]],
},
update: {
filter: [["ownerId", "=", "$SESSION_USER_ID"]],
},
delete: {
filter: [["ownerId", "=", "$SESSION_USER_ID"]],
},
},
},
};
describe("Access Control", () => {
test("user can read their own todos", async () => {
const userA = createTestClient("user-a");
await userA.insert("todos", {
id: "my-todo",
title: "My private todo",
completed: false,
ownerId: "user-a",
priority: 0,
tags: new Set(),
});
const result = await userA.fetch(
userA.query("todos").where("id", "=", "my-todo").build()
);
expect(result.size).toBe(1);
await userA.disconnect();
});
test("user cannot read other user's todos", async () => {
const userA = createTestClient("user-a");
const userB = createTestClient("user-b");
await userA.insert("todos", {
id: "a-private",
title: "User A private",
completed: false,
ownerId: "user-a",
priority: 0,
tags: new Set(),
});
// User B queries for user A's todo
const result = await userB.fetch(
userB.query("todos").where("id", "=", "a-private").build()
);
// Access control should prevent user B from seeing it
expect(result.size).toBe(0);
await userA.disconnect();
await userB.disconnect();
});
test("user cannot insert with different ownerId", async () => {
const userA = createTestClient("user-a");
// Attempting to insert a todo owned by a different user
await expect(
userA.insert("todos", {
id: "spoofed",
title: "Spoofed ownership",
completed: false,
ownerId: "user-b", // Wrong owner
priority: 0,
tags: new Set(),
})
).rejects.toThrow();
await userA.disconnect();
});
test("user cannot update another user's todo", async () => {
const userA = createTestClient("user-a");
const userB = createTestClient("user-b");
await userA.insert("todos", {
id: "protect-me",
title: "Protected",
completed: false,
ownerId: "user-a",
priority: 0,
tags: new Set(),
});
await expect(
userB.update("todos", "protect-me", (todo) => {
todo.completed = true;
})
).rejects.toThrow();
// Verify it wasn't changed
const result = await userA.fetch(
userA.query("todos").where("id", "=", "protect-me").build()
);
expect([...result.values()][0].completed).toBe(false);
await userA.disconnect();
await userB.disconnect();
});
});Testing Mutations
describe("Triplit Mutations", () => {
test("insert returns the inserted entity", async () => {
const client = createTestClient();
const result = await client.insert("todos", {
id: "ins-1",
title: "Insert test",
completed: false,
priority: 5,
tags: new Set(["test"]),
ownerId: "test-user-1",
});
expect(result.output?.id).toBe("ins-1");
expect(result.output?.title).toBe("Insert test");
await client.disconnect();
});
test("update modifies specific fields", async () => {
const client = createTestClient();
await client.insert("todos", {
id: "upd-1",
title: "Original",
completed: false,
priority: 0,
tags: new Set(),
ownerId: "test-user-1",
});
await client.update("todos", "upd-1", (todo) => {
todo.completed = true;
todo.priority = 10;
});
const result = await client.fetchById("todos", "upd-1");
expect(result?.completed).toBe(true);
expect(result?.priority).toBe(10);
expect(result?.title).toBe("Original"); // Unchanged
await client.disconnect();
});
test("delete removes the entity", async () => {
const client = createTestClient();
await client.insert("todos", {
id: "del-1",
title: "Delete me",
completed: false,
priority: 0,
tags: new Set(),
ownerId: "test-user-1",
});
await client.delete("todos", "del-1");
const result = await client.fetchById("todos", "del-1");
expect(result).toBeNull();
await client.disconnect();
});
test("Set field supports add and delete operations", async () => {
const client = createTestClient();
await client.insert("todos", {
id: "set-1",
title: "Set test",
completed: false,
priority: 0,
tags: new Set(["existing"]),
ownerId: "test-user-1",
});
await client.update("todos", "set-1", (todo) => {
todo.tags.add("new-tag");
todo.tags.delete("existing");
});
const result = await client.fetchById("todos", "set-1");
expect(result?.tags.has("new-tag")).toBe(true);
expect(result?.tags.has("existing")).toBe(false);
await client.disconnect();
});
});Testing Real-Time Subscriptions
describe("Real-Time Subscriptions", () => {
test("subscription fires on insert", async () => {
const client = createTestClient();
const updates: Map<string, any>[] = [];
const unsubscribe = client.subscribe(
client.query("todos").where("ownerId", "=", "test-user-1").build(),
(result) => updates.push(result)
);
await new Promise(resolve => setTimeout(resolve, 10));
await client.insert("todos", {
id: "sub-1",
title: "Subscription trigger",
completed: false,
priority: 0,
tags: new Set(),
ownerId: "test-user-1",
});
await new Promise(resolve => setTimeout(resolve, 10));
const lastUpdate = updates[updates.length - 1];
expect(lastUpdate?.has("sub-1")).toBe(true);
unsubscribe();
await client.disconnect();
});
test("subscription fires on update", async () => {
const client = createTestClient();
await client.insert("todos", {
id: "sub-upd",
title: "Before update",
completed: false,
priority: 0,
tags: new Set(),
ownerId: "test-user-1",
});
const updates: Map<string, any>[] = [];
const unsubscribe = client.subscribe(
client.query("todos").where("id", "=", "sub-upd").build(),
(result) => updates.push(result)
);
await new Promise(resolve => setTimeout(resolve, 10));
await client.update("todos", "sub-upd", (todo) => {
todo.title = "After update";
});
await new Promise(resolve => setTimeout(resolve, 10));
const lastUpdate = updates[updates.length - 1];
const todo = lastUpdate?.get("sub-upd");
expect(todo?.title).toBe("After update");
unsubscribe();
await client.disconnect();
});
});CI/CD Configuration
name: Triplit Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm"
- run: npm ci
- name: Run schema tests
run: npx vitest run tests/schema
- name: Run query tests
run: npx vitest run tests/queries
- name: Run access control tests
run: npx vitest run tests/access-control
- name: Run mutation tests
run: npx vitest run tests/mutationsMonitoring Triplit in Production
Access control bugs in Triplit can silently expose user data — a misconfigured permission filter and one user starts seeing another's todos. Unit tests catch schema-level issues. Continuous end-to-end tests catch runtime permission failures.
HelpMeTest lets you run multi-user access control tests against your production Triplit server on a 5-minute cadence. Write the test once: "User A's todos should not be visible to User B." HelpMeTest runs it continuously and alerts you if the access control breaks.
Summary
Triplit testing covers five areas:
- Schema — collection completeness, field types, defaults, optional field handling
- Queries — filter, order, limit, set membership, related collection includes
- Access control — read/write restrictions, cross-user isolation, ownerId enforcement
- Mutations — insert, update, delete, Set field operations
- Subscriptions — reactive updates on insert, update, and delete
Schema and access control tests provide the highest ROI. TypeScript catches many schema issues at compile time, but access control rules need runtime testing with multiple simulated users to catch permission boundary bugs.