Test your application locally #
On this page
Prompt:
Make the tests run without the cloud: fast, offline, and the same result every time.
Also works:
- "Test the records layer without touching the development database."
- "The suite hangs when I have no connection; fix that."
This page adds offline tests to an application you already have. To start a new service instead, use the scaffold line in Starting a new service. It writes a test script and a first test file. For a new service that keeps its data in the database, start with Build a database-backed service, which also installs the test engine.
The Database double at @turnzero/database/testing is for tests, not for running or previewing the application itself. To try the application, use a local run against the development database. If development is enabled, you can instead deploy to that environment.
A provisioned local run uses the pooled address, port 6432, through APP_DATABASE_URL; APP_DATABASE_DIRECT_URL names the direct port, 5432. Code that holds a server session across transactions must read APP_DATABASE_DIRECT_URL locally and when deployed. Offline tests do not exercise the pooler; a local run using the provisioned APP_DATABASE_URL does.
Run against your own PostgreSQL needs no Turn Zero sign-in and uses the application's real pg.Pool. Use that route only if the application reads none of TURNZERO_CLOUD_APP_TOKEN, TURNZERO_CLOUD_API or TURNZERO_CLOUD_GATEWAY_URL.
Tests using the Database double need PGlite as a development dependency. Install it with npm install --save-dev @electric-sql/pglite@0.5.8 (step 1). Run the tests with npm test (step 4). If your application uses pg alone, Without the Database package shows a query-only test using PGlite directly, with no Turn Zero sign-in or library download.
What your AI tool does #
- Checks which backend packages the application has under
app/lib/. For each one, it imports the package's test double from@turnzero/<name>/testing, next to the client it imports from@turnzero/<name>. - For database tests, installs
@electric-sql/pgliteat the version the Database package's contract specifies. The other doubles need no additional dependency. - Finds any module that reads a setting as soon as it is imported, such as a data layer that opens its pool from
APP_DATABASE_URL. It changes that module into a factory: a function that takes the pool as an argument. - Writes each package-double test file so it builds its doubles once, calls
reset()between tests, and closes the doubles at the end. The direct PGlite example empties its table between tests instead. - Runs the suite with
npm test, and reports how many tests ran and how long they took. - Asks you nothing: it writes only to your project, and it calls no platform action.
What you need #
- Node.js 24 or later, and npm, installed on your computer (What your computer needs). The samples use Node's built-in test runner, so you need no other test runner.
Before your AI starts #
For the AI tool: Check the following before starting.
- For the package-double route, the Database package under
app/lib/database/, declared asfile:lib/database, at a version whose entry includes thetestingsubpath (Use the library). Each other package the tests use must be in place the same way. The direct PGlite example needs none of these packages. - The schema, kept as
.sqlfiles in order undermigrations/(Add a database). - A
testentry underscriptsinpackage.json, such asnode --test, sonpm testruns the suite.
Steps #
Most applications have a data layer that reads the database. Steps 1 to 5 test that layer over the database double. Step 6 adds the other doubles. A double reaches nothing outside the test's process, so the tests need no account, no connection, and no environment file.
1. Install the engine #
The database double runs your migrations and queries on PGlite, a build of PostgreSQL that runs inside the Node.js process. Install it as a development dependency, so it is never part of the deployed image. Use the version the package's contract names in its Verification section.
npm install --save-dev @electric-sql/pglite@0.5.8
2. Write the data layer over a pool #
A module that opens its pool from APP_DATABASE_URL when it is imported cannot be tested without that setting. And a test that sets it reaches the development database. So write the data layer as a factory over a pool, createDataLayer(pool): a function that takes the pool and returns the layer. Keep the one function that opens the live pool beside it, as the data module in Add a database does. Only the process entry, the script that starts your server, calls that function. No module opens a pool when it is imported.
The sample's one migration, migrations/0001_notes.sql:
CREATE TABLE notes (
id bigserial PRIMARY KEY,
title text NOT NULL CHECK (title <> '')
);
The data layer the tests call:
// src/db.mjs: the data layer over any pool with the pg.Pool shape: the live one, or a test double's.
export function createDataLayer(pool) {
return {
async addNote(title) {
const { rows } = await pool.query('INSERT INTO notes (title) VALUES ($1) RETURNING id, title', [title]);
return rows[0];
},
async countNotes() {
const { rows } = await pool.query('SELECT count(*)::int AS n FROM notes');
return rows[0].n;
},
};
}
A server module follows the same rule. It builds its handlers over the layer it is given. Only its entry block, which runs when the module is the process's main script, opens the live pool. So a test can import the module without starting the server.
3. Write the test file #
createDatabaseDouble({ engine, files }) from @turnzero/database/testing takes the engine and your migration files. migrationsFrom(dir) reads a folder of migration files. The factory first checks the engine with one probe statement. Then it applies the files with the package's own migration function, each file in its own transaction, as when the application starts. So a broken migration makes the construction fail with the engine's error before any test runs. The factory returns { pool, applied, statements, reset, close }.
Construct the double once per test file, because the engine takes about a second to start. Pass createDataLayer(double.pool) to the code under test. Call reset() before each test and close() at the end.
// test/notes.test.mjs
import assert from 'node:assert/strict';
import { after, before, beforeEach, test } from 'node:test';
import { fileURLToPath } from 'node:url';
import { PGlite } from '@electric-sql/pglite';
import { createDatabaseDouble, migrationsFrom } from '@turnzero/database/testing';
import { createDataLayer } from '../src/db.mjs';
const MIGRATIONS = fileURLToPath(new URL('../migrations/', import.meta.url));
let double;
let db;
// One engine for the file, with the migrations applied, since it takes about a second to start.
before(async () => {
double = await createDatabaseDouble({ engine: new PGlite(), files: migrationsFrom(MIGRATIONS) });
db = createDataLayer(double.pool);
});
// Every table but the migration ledger emptied, so each test starts from the schema alone.
beforeEach(() => double.reset());
after(() => double.close());
test('the migration applies', () => {
assert.deepEqual(double.applied, ['0001_notes.sql']);
});
test('addNote adds a row, its bigint id read back as a string', async () => {
assert.deepEqual(await db.addNote('first'), { id: '1', title: 'first' });
assert.equal(await db.countNotes(), 1);
});
test('the schema refuses an empty title, with the server code of a check', async () => {
await assert.rejects(db.addNote(''), { code: '23514' });
assert.equal(await db.countNotes(), 0);
});
To test the routes too, start the server over the same layer on port 0, which lets the system pick a free port. The template's test in Build a database-backed service does this. For a plain pg application, the server test below runs offline over PGlite. If you use Vitest, raise hookTimeout. On a busy machine, the engine can take longer to start than Vitest's ten-second default.
4. Run the tests #
Run npm test in app/, the folder that holds your application's package.json. To call Node's built-in runner directly, run node --test with nothing after it: it finds the test files itself. To name the files, give a quoted pattern such as node --test "test/**/*.test.mjs", not a folder such as test/. In Windows PowerShell, run npm as What your computer needs describes.
5. Know what the database double reproduces #
The double answers as PostgreSQL does. It also applies your migrations as the migration walk does when your application starts:
poolhas the shape your application already uses:query(text, values?)orquery({ text, values }),connect(), andend(). It serves one caller at a time, so the statements of two transactions never mix.- The double's
pool.queryruns all statements in query text that has no values, so a migration file of several statements runs as it does under node-pg. A text with values runs as one statement, and so does a query object that setsname,queryMode: 'extended', orrows, as under node-pg. - A
bigintsuch ascount(*)comes back as a string, as it does from thepgdriver, so writecount(*)::intwhere your code needs a number. - When a query breaks a constraint, the error carries the server's own code, such as
23514for a check and23503for a foreign key. appliedlists, in order, the migration files the construction applied.statementsrecords every statement the pool ran, including the migrations' statements. Each entry is the statement's text. Where the statement had values, the entry adds--and the JSON of those values.reset()empties every table except the migration ledger, and clearsstatements. The ledger keeps its rows, so running the application's own migration function again applies nothing.
It does not reproduce the platform around the database. Test these in a local run against the development database, as Run your app on your computer describes, or against a deployed environment:
- A second database session. The engine has only one session, so nothing competes with the test's.
- A lost connection, a restart, or a reconnect. The engine runs inside the test's process with no network connection, so it never loses one.
- A client held too long. While a client is checked out, a
pool.querywaits. Past the double's limit, 5 seconds by default, it fails withsession_held. - The connection string, TLS, and
sslmode. The double never reads the setting. - The database role's connection limit, and the overlap during a deploy or a failover. The pool's maximum,
APP_DATABASE_CONNECTION_LIMIT, is read only by the function that builds the live pool, and the tests never call that function. - Provisioning, metering, and credential rotation.
- The managed server's version and time zone. So a timestamp that the server turns into text can differ.
Without the Database package #
You can test a plain pg application's data layer with PGlite directly. Install the development dependency in step 1, then keep the migration and src/db.mjs from step 2. No Turn Zero account, command, token, or library package is needed. npm needs a connection for the initial install; the tests run offline afterward. Use these pre-deploy tests in an unattended run that must not write credentials to disk: these tests need no .env or platform credential file. They test migration SQL and the data layer; the server test below also checks the HTTP routes.
Save the following as test/notes_without_package.test.mjs instead of the test file in step 3. It reads the same SQL file, starts an in-memory database, and supplies the query(text, values) method the data layer calls. Your application's live entry still opens its real pg.Pool; this test never imports that entry or reads its connection setting.
// test/notes_without_package.test.mjs
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { after, before, beforeEach, test } from 'node:test';
import { PGlite } from '@electric-sql/pglite';
import { createDataLayer } from '../src/db.mjs';
let engine;
let db;
before(async () => {
engine = await PGlite.create();
const schema = await readFile(new URL('../migrations/0001_notes.sql', import.meta.url), 'utf8');
await engine.exec(schema);
// Only the query method this data layer uses, not a replacement for pg.Pool.
db = createDataLayer({ query: (text, values) => engine.query(text, values) });
});
beforeEach(() => engine.exec('TRUNCATE notes RESTART IDENTITY'));
after(async () => { await engine?.close(); });
test('a parameterized insert preserves the title', async () => {
assert.equal(await db.countNotes(), 0);
const note = await db.addNote("Sam's note");
assert.equal(note.title, "Sam's note");
assert.equal(await db.countNotes(), 1);
});
test('the schema refuses an empty title', async () => {
assert.equal(await db.countNotes(), 0);
await assert.rejects(db.addNote(''), { code: '23514' });
assert.equal(await db.countNotes(), 0);
});
Run npm test, using the node --test script from the prerequisites. Both tests pass. The table is emptied before each test, and closing the engine discards the in-memory database.
This example checks SQL, parameters, constraints, and the application's data-layer functions. Its small adapter supplies no connect(), release(), rowCount, query objects, or pool events. It does not reproduce the pg driver's type parsing: a bigint can be read differently. It applies this one schema file without a migration ledger.
You can test a migration helper of your own through the same query(text, values) adapter, including its ledger reads and writes. engine.query takes one statement per call; for a migration file with several statements and no values, route that call to engine.exec.
PGlite's one session does not test a helper's lock against another process; a helper that holds its lock across transactions must use the direct setting when deployed.
To test the HTTP routes too, save the following as src/server.mjs. Its createApp(db) builds the server over the data layer from step 2. Importing it opens no pool and starts no listener; only its entry block imports pg, reads APP_DATABASE_URL, and starts the live server.
// src/server.mjs: the HTTP handlers over the data layer it is given. Only the entry block opens the live pool.
import { createServer } from 'node:http';
import { pathToFileURL } from 'node:url';
import { createDataLayer } from './db.mjs';
export function createApp(db) {
return createServer(async (request, response) => {
const send = (status, body) => {
response.writeHead(status, { 'content-type': 'application/json' });
response.end(JSON.stringify(body));
};
try {
if (request.method === 'GET' && request.url === '/health') return send(200, { ok: true });
if (request.method === 'GET' && request.url === '/notes/count') return send(200, { count: await db.countNotes() });
if (request.method === 'POST' && request.url === '/notes') {
let text = '';
for await (const chunk of request) text += chunk;
const { title } = JSON.parse(text || '{}');
return send(201, await db.addNote(String(title ?? '')));
}
return send(404, { error: 'not_found' });
} catch (error) {
if (error.code === '23514') return send(400, { error: 'invalid_title' });
return send(500, { error: 'internal' });
}
});
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const { default: pg } = await import('pg');
const pool = new pg.Pool({ connectionString: process.env.APP_DATABASE_URL });
createApp(createDataLayer(pool)).listen(Number(process.env.PORT ?? 8080));
}
Save this test as test/server_without_package.test.mjs, beside the first test file. It starts the server on port 0 over the same in-memory database, then sends HTTP requests to the port the system chooses.
// test/server_without_package.test.mjs
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { readFile } from 'node:fs/promises';
import { after, before, beforeEach, test } from 'node:test';
import { PGlite } from '@electric-sql/pglite';
import { createDataLayer } from '../src/db.mjs';
import { createApp } from '../src/server.mjs';
let engine;
let server;
let base;
before(async () => {
engine = await PGlite.create();
const schema = await readFile(new URL('../migrations/0001_notes.sql', import.meta.url), 'utf8');
await engine.exec(schema);
const db = createDataLayer({ query: (text, values) => engine.query(text, values) });
server = createApp(db).listen(0);
await once(server, 'listening');
base = `http://127.0.0.1:${server.address().port}`;
});
beforeEach(() => engine.exec('TRUNCATE notes RESTART IDENTITY'));
after(async () => {
server?.close();
await engine?.close();
});
test('a POST saves a note, and the count reads it back', async () => {
const saved = await fetch(`${base}/notes`, { method: 'POST', body: JSON.stringify({ title: "Sam's note" }) });
assert.equal(saved.status, 201);
assert.equal((await saved.json()).title, "Sam's note");
const counted = await fetch(`${base}/notes/count`);
assert.deepEqual(await counted.json(), { count: 1 });
});
test('an empty title is refused, and nothing is saved', async () => {
const refused = await fetch(`${base}/notes`, { method: 'POST', body: JSON.stringify({ title: '' }) });
assert.equal(refused.status, 400);
const counted = await fetch(`${base}/notes/count`);
assert.deepEqual(await counted.json(), { count: 0 });
});
Run npm test again. The server test saves a note, reads its count, and checks that an empty title is refused without saving a row. It tests the HTTP routes and data layer offline, using the schema from step 2. It does not test the pg driver, the live pool, or the migration ledger.
Use the Database double above where you need its pool interface and migration handling. Use a PostgreSQL server for tests of the actual driver, concurrent sessions, TLS, connection loss, or pool limits. A local run against the development database tests the managed connection; that route requires Turn Zero sign-in.
To start the application itself against your own PostgreSQL, see Run against your own PostgreSQL.
Test a CommonJS data layer #
Keep migrations/0001_notes.sql and save these two files as .cjs. They stay CommonJS whether your package.json sets "type": "module" or leaves type unset.
// src/db.cjs: the same data layer in CommonJS, over any pool with the pg.Pool shape.
function createDataLayer(pool) {
return {
async addNote(title) {
const { rows } = await pool.query('INSERT INTO notes (title) VALUES ($1) RETURNING id, title', [title]);
return rows[0];
},
async countNotes() {
const { rows } = await pool.query('SELECT count(*)::int AS n FROM notes');
return rows[0].n;
},
};
}
module.exports = { createDataLayer };
Save the test as test/notes_without_package.test.cjs:
// test/notes_without_package.test.cjs
const assert = require('node:assert/strict');
const { readFile } = require('node:fs/promises');
const { join } = require('node:path');
const { after, before, beforeEach, test } = require('node:test');
const { PGlite } = require('@electric-sql/pglite');
const { createDataLayer } = require('../src/db.cjs');
let engine;
let db;
before(async () => {
engine = await PGlite.create();
const schema = await readFile(join(__dirname, '..', 'migrations', '0001_notes.sql'), 'utf8');
await engine.exec(schema);
// Only the query method this data layer uses, not a replacement for pg.Pool.
db = createDataLayer({ query: (text, values) => engine.query(text, values) });
});
beforeEach(() => engine.exec('TRUNCATE notes RESTART IDENTITY'));
after(async () => { await engine?.close(); });
test('a parameterized insert preserves the title', async () => {
assert.equal(await db.countNotes(), 0);
const note = await db.addNote("Sam's note");
assert.equal(note.title, "Sam's note");
assert.equal(await db.countNotes(), 1);
});
test('the schema refuses an empty title', async () => {
assert.equal(await db.countNotes(), 0);
await assert.rejects(db.addNote(''), { code: '23514' });
assert.equal(await db.countNotes(), 0);
});
Run npm test with the same node --test script. These tests need no Turn Zero account, token or library package.
6. Use the other doubles #
Each of the other doubles stands in for one platform service, in memory, so your code keeps using the real client. Build the client over double.transport, the function the client sends its requests through. If your application's own transport wraps the global fetch, keep that transport. Then stub the global fetch with double.fetch, that is, replace it for the test. Each double records every call, so your tests can check them.
Each package page shows its double in one short test, in its section Test with the double. Each package's integration guide lists every option, every recorded member, and every call that scripts the double's answers. Your AI tool reads that guide with read_library, giving the package's name in entry and the file features/<name>/integration.md in file.
| Package | Factory | How the client connects | Set-up | Sample |
|---|---|---|---|---|
| Database | createDatabaseDouble({ engine, files }) |
Pass double.pool to the data layer. |
Once per file, as step 3 shows. | Steps 2 and 3 |
| Storage | createStorageDouble(options) |
new StorageWireClient(double.transport), or stub fetch. |
Once per file. reset() forgets every area, so declare areas in each test. |
Storage |
| Logging | createLoggingDouble(options) |
new LogClient(double.transport, { environment: 'local' }), or stub fetch. |
Call await client.flush() before reading the double, and await client.close() at the end. |
Logging |
| Egress | createEgressDouble(options) |
EgressClient over double.transport, or stub fetch. |
Once per file. Declare each upstream with double.declare(name, handler, { application }). Pass credential: 'session' to the factory where your transport sends the environment header. |
Egress |
| Schedule | createScheduleDouble(router, { now }) |
Pass it the router that createScheduleRouter builds from manifest.json and your handlers. Then call fire(schedule, options). |
Once per server. reset() empties double.fires. |
Schedule |
| AI Allowance | createAiAllowanceDouble(options) |
Pass double.transport to generateText, or stub fetch. |
Set quota, and set prices where the test checks dollar amounts. Queue each answer with double.prime(...). |
AI Allowance |
| Account | await createAccountDouble(options) |
double.client(), or the real client over the double's functions, or stub fetch. |
Once per file, before the tests. Sign users in with signIn(user). |
Account |
| Push | createPushDouble(options) |
createPushClient({ transport: double.transport }), or pass double.fetch as the client's fetch. |
Once per file. Register devices with double.register(device), and read double.sends. |
Push |
| Issue Tracking | createIssueTrackingDouble(options) |
Call double.createSpace(), then double.gatewayView({ space }) with the space.id it returns. The view reaches the space through the gateway, as your deployed backend does. Build createIssueTrackingClient(view.transport) with no options. createIssueTrackingClientV2(view.transport) takes the same transport for submit, read, list, and search. |
Once per file. reset() empties every space, so seed a space and take its view in each test. The view takes no quantity and no stored-data state. |
Issue Tracking |
createEmailDouble(options) |
createEmailClient({ transport: double.transport }), or pass double.fetch as the client's fetch. |
Once per file. Give the plan's counts in cells and the clock in now, and read double.sends. |
Each double comes with its package, which your AI tool takes from the library after you sign in. Before you sign in, test code that calls storage over plain fetch, as Call storage without end-user sign-in does, against your own stand-in for the global fetch, answering in the shapes File routes lists. The database's package-free way is Without the Database package. For sign-in without a package, test the server offline against a local stand-in, with no Turn Zero connection.
The account double and a native app's bearer #
To test a native app's request in a backend test, you need nothing new. Send the session that signIn(user) returns as Authorization: Bearer <session>. The server in Tell which user sent a request reads it as it reads the cookie. The Account package's integration guide has a sample for Node's built-in runner that runs with node --test. Your AI tool reads that guide with read_library, using entry: "account" and file: "features/account/integration.md".
The double provides no token endpoint, no refresh, and no session list. Test the app's sign-in, its refresh, and its session list against the application's own realm, its list of users, as Sign in from a native app describes. On an application with one environment, that is production's realm. Where you turned development on, it is development's realm.
A local run can also use a real session with no person signing in. Sign a test end user in on that realm and pass its session to the run, as Test sign-in with test end users describes.
Expected result #
npm test runs the suite offline, without an environment file or a development database. The Database double empties tables with reset(); the direct PGlite example uses TRUNCATE. The other doubles run in the same process.
Refusals #
The doubles' refusals are errors thrown in the test process. A Structured Query Language (SQL) error carries the server's own five-character code, with the driver's message and members. Where the test checks for a refusal on purpose, assert its code instead of applying the remedy.
| Refusal | Cause | Remedy |
|---|---|---|
engine_required |
No engine was given, or its response to SELECT 1 lacks rows or a numeric rowCount. |
Pass a PGlite 0.5.8 instance as engine. |
session_held |
A second caller waited too long, 5 seconds by default, for a checked-out client. | Query through the client you hold, and release it in a finally. |
pool_ended |
connect() or query() was called after pool.end(). |
End the pool only at the end of the file. |
APP_DATABASE_URL absent |
The test imported a module that opens its pool when it is imported. | Make the data layer a factory over a pool, as step 2 shows. Never set the variable for a test: only the process entry reads it. |
This table lists the refusals a test most often meets from the Database double. Each other double's refusals are listed on its package page, under Test with the double: Storage, Logging, Egress, Schedule, AI Allowance, Account, Push, Issue Tracking, and Email. The refusals page lists all of the platform's refusals, with the cause and remedy of each.
Related #
- Check data after a restart or idle stop verifies a deployed environment using an existing record, without adding production test data.
- The Database, Storage, Logging, Egress, Schedule, AI Allowance, Account, Push, Issue Tracking, and Email pages state what each package provides.
- Add a database covers the declaration, the setting, the migration files, and the pool's size.
- Run your app on your computer covers the environment file and the settings a live local run reads.
- Use the library installs a package's compiled code, the
testingsubpath with it. - Test sign-in with test end users signs a test end user in on the hosted realm, for the parts of a test that need the live service.