Real Postgres in Your Test Suite Without Running a Database

Database-dependent logic usually gets tested one of two bad ways. Either the data layer is mocked — fast, and blind to everything the database actually enforces — or the suite needs a live Postgres, which means containers, ports, migrations, cleanup between tests, and a CI job that fails for reasons unrelated to the code.
There is a third option that has become practical: run Postgres itself, compiled to WebAssembly, inside the test process. No server, no container, no port. A real engine with real constraints.
import { PGlite } from "@electric-sql/pglite";
const db = new PGlite(); // in-memory Postgres
await db.exec(readFileSync("schema.sql", "utf8"));
That is the whole setup. From there you are talking to Postgres.
What mocking cannot see
The reason this matters is that the most valuable guarantees in a relational schema are enforced by the database, and a mock agrees with whatever you tell it.
Constraints. A partial unique index that prevents a second successful payment for the same order is the thing standing between you and double-charging a customer. A mocked repository will cheerfully accept both rows.
CREATE UNIQUE INDEX one_successful_payment_per_order
ON payments (order_id) WHERE status = 'succeeded';
await db.query(`INSERT INTO payments (order_id, status) VALUES ($1, 'succeeded')`, [id]);
await assert.rejects(
db.query(`INSERT INTO payments (order_id, status) VALUES ($1, 'succeeded')`, [id]),
/one_successful_payment_per_order/,
);
That test is meaningful only against a real engine. It is the difference between believing you have idempotency and having it.
Transactions and rollback. Whether a failure half-way through a multi-table write leaves consistent data is a property of transaction handling, not of your code's happy path.
Cascades and referential integrity. ON DELETE CASCADE either removes the right rows or quietly
removes more than you intended. You find out by deleting and counting.
Row-level security. If tenant isolation is enforced by policies, the only honest test is to set the session role and confirm another tenant's rows are invisible. A mock cannot be wrong about this, which is exactly the problem.
Migrations. Applying your real migration files to an empty database, in order, every run, tests the one script that will run against production data.
The pattern that keeps it fast
The cost is creating the schema, not running the queries. Build once per suite, isolate per test with transactions:
let db;
before(async () => {
db = new PGlite();
await db.exec(readFileSync("migrations/001_init.sql", "utf8"));
await db.exec(readFileSync("migrations/002_payments.sql", "utf8"));
});
beforeEach(() => db.query("BEGIN"));
afterEach(() => db.query("ROLLBACK"));
Every test starts from the same committed state and leaves nothing behind. No truncation, no ordering dependencies, no leakage between tests. For suites where tests must commit, create a fresh instance per file instead — construction is cheap enough that this is viable.
Where it does not reach
Be clear about the limits so nobody mistakes this for a production equivalent:
- Extensions. Many are unavailable or need an explicit build. If you depend on PostGIS or
pg_cron, check before committing to the approach. - Concurrency. It is single-connection. Genuine lock contention, deadlock ordering and
SELECT ... FOR UPDATE SKIP LOCKEDbehaviour under parallel workers need a real server. - Performance. Query plans and timings tell you nothing useful about production. Do not benchmark here.
- Version drift. Pin the version and keep it aligned with production, or you are testing a different database from the one you deploy to.
The honest framing is that this covers correctness of schema and logic, not behaviour under load. For most application test suites that is the overwhelming majority of the value.
What it changes in practice
The immediate effect is that tests nobody was writing become easy enough to write. Constraint tests, cascade tests and isolation tests all had the same previous cost — stand up a database — so they were skipped, and the guarantees went unverified until something went wrong in production.
The second effect is on CI: no service containers, no readiness waiting, no port conflicts between parallel jobs. The suite runs anywhere Node runs.
The third is subtler and matters most. When writing a constraint is as testable as writing an
if, more invariants end up in the schema where the database enforces them for every writer —
instead of in application code, where they hold only for the paths that remembered to check.


