Testing
You can test most of an app in Deno without a browser. Use in-memory storage for store logic, and a real server started inside the test for sync and sharing.
| Layer | Covers | How |
|---|---|---|
| Model | Your store code, migrations, merges | Store or CloudStore with memory storage |
| Integration | Sync, blobs, share links | A client against startTestServer() |
| Browser | Sign-in redirect, service worker, IndexedDB | Manual, or a browser automation tool |
Model tests
Let tests pass in the storage backend:
// store.ts
import { CloudStore, type StoreDatabase } from '@civility/cloud'
import { IDBStorage } from '@civility/cloud/storage/idb'
type Item = { text: string }
export function createStore(
db: StoreDatabase = new IDBStorage({ id: APP_ID }),
) {
const store = new CloudStore({
storage: { db },
collections: ['items'],
versions: [{
version: '1.0.0',
schema: { type: 'object', properties: { items: { type: 'object' } } },
}],
cloud: { appId: APP_ID },
})
return { store, items: store.collection<Item>('items') }
}
@civility/cloud/storage/memory exports MemoryStorage and MemoryBlobStorage. They need no id and keep nothing after the process ends.
// store.test.ts
import { assertEquals } from '@std/assert'
import { BlobStore } from '@civility/cloud'
import {
MemoryBlobStorage,
MemoryStorage,
} from '@civility/cloud/storage/memory'
import { createStore } from './store.ts'
Deno.test('set stores an item', async () => {
const { store, items } = createStore(new MemoryStorage())
await items.set('1', { text: 'hello' })
assertEquals((await items.get('1'))?.text, 'hello')
await store.dispose()
})
Deno.test('blobs round-trip', async () => {
const blobs = new BlobStore(new MemoryBlobStorage())
const hash = await blobs.put(new Uint8Array([1, 2, 3]), 'image/png')
assertEquals((await blobs.get(hash))?.type, 'image/png')
})
A server for integration tests
startTestServer() from @civility/cli/testing starts a server in the test process on a free port.
deno add jsr:@civility/cli
import { startTestServer } from '@civility/cli/testing'
const server = await startTestServer() // { url, close() }
// point clients at server.url
await server.close()
Each call gives a new, empty server: an in-memory database, blob storage in a temporary directory that close() deletes, and no scheduled jobs. Import it from tests only.
Sign in from a test
A test cannot use the consent page, so create an account over HTTP and set the token directly. The test server has no email adapter, so sign-up returns a token at once.
// test/auth.ts
export async function signUp(url: string, appId: string): Promise<string> {
// Email and name must be unique on the server.
const unique = `${Date.now()}-${Math.random().toString(36).slice(2)}`
const res = await fetch(`${url}/api/v1/auth/signup`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: `${unique}@test.dev`,
name: unique,
password: 'password123',
}),
})
const token = (await res.json()).data.token
// Create the app id for this account.
await fetch(`${url}/api/v1/apps`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ id: appId, name: 'Test App' }),
})
return token
}
Only tests sign in with a password. Apps use the sign-in flow.
Then connect the client:
store.connect(server.url)
store.setToken(token)
Run sync in a test
The background loop runs every 30 seconds. In a test, run one cycle and await it:
await store.sync()
Listen for
errorevents. The background loop does not throw, and blob transfer and cross-app errors are reported only as events.import type { SyncErrorEvent } from '@civility/cloud' store.addEventListener('error', (e) => { const { error, context } = e as SyncErrorEvent console.error(context.phase, error.code, error.message) })Each account has its own copy of an app, so two test accounts on one server can use the same app id without seeing each other's data.
Example: two devices
import { assertEquals } from '@std/assert'
import { startTestServer } from '@civility/cli/testing'
import { MemoryStorage } from '@civility/cloud/storage/memory'
import { createStore } from './store.ts'
import { signUp } from './test/auth.ts'
Deno.test('items sync across devices', async () => {
const server = await startTestServer()
try {
const token = await signUp(server.url, APP_ID)
const a = createStore(new MemoryStorage())
a.store.connect(server.url)
a.store.setToken(token)
await a.items.set('1', { text: 'hello' })
await a.store.sync()
const b = createStore(new MemoryStorage())
b.store.connect(server.url)
b.store.setToken(token)
await b.store.sync()
assertEquals((await b.items.get('1'))?.text, 'hello')
await a.store.dispose()
await b.store.dispose()
} finally {
await server.close()
}
})
Test share links
Publish with a signed-in client, then read as a visitor with no token. See Share links.
import { CloudStore, getShare } from '@civility/cloud'
import { MemoryStorage } from '@civility/cloud/storage/memory'
const store = new CloudStore({
storage: { db: new MemoryStorage() },
collections: ['items'],
versions: [{
version: '1.0.0',
schema: { type: 'object', properties: { items: { type: 'object' } } },
}],
cloud: { appId: APP_ID },
share: { appShareUrl: 'https://app.example/' },
})
store.connect(server.url)
store.setToken(token)
await store.collection('items').set('1', { text: 'hello' })
const { id } = await store.share.publish({ collection: 'items', docId: '1' })
await store.sync() // send the share record to the server
const doc = await getShare(APP_ID, id, { server: server.url, schema: Item })
assertEquals(doc.text, 'hello')
await store.share.revoke(id)
await store.sync()
// getShare now rejects with code 'sync.share_not_found'
Item here is a Zod schema. A blob referenced by a shared record is served at GET /api/v1/shares/<appId>/<shareId>/blob/<hash>; fetch it with getShareBlob.
Test three states: not shared (404), published (200), revoked (404).
Run a server by hand
For testing in a browser, run a server that keeps its data:
export CIVILITY_AUTH_SECRET=$(civ api gen-secret)
civ api start --port 3848 --db-path ./.data/civility.db
Blobs go to ./.data/blobs, or the directory in CIVILITY_BLOB_PATH, until storage is configured in /admin/storage.
Serve your app, then connect it to http://localhost:3848. The first time, the consent page offers Create & Authorize, which creates your app id on that server. The API allows requests from any origin, so your app can run on another port.
What needs a browser
- The sign-in redirect to the consent page and back, finished by
restore(). - The service worker, including the blob proxy.
- IndexedDB: that data is still there after a reload.
- Upgrades: that a store written by an older release opens after a schema change.