pgsql-test
pgsql-test gives you instant, isolated PostgreSQL databases for each test — with automatic transaction rollbacks, context switching, and clean seeding. Forget flaky tests and brittle environments. Write real SQL. Get real coverage. Stay fast.
Install
npm install pgsql-test
Features
- ⚡ Instant test DBs — each one seeded, isolated, and UUID-named
- 🔄 Per-test rollback — every test runs in its own transaction or savepoint
- 🛡️ RLS-friendly — test with role-based auth via
.setContext()
- 🌱 Flexible seeding — run
.sql files, programmatic seeds, or even load fixtures
- 🧪 Compatible with any async runner — works with
Jest, Mocha, etc.
- 🧹 Auto teardown — no residue, no reboots, just clean exits
Tutorials
📚 Learn how to test PG with pgsql-test →
Using with Supabase
If you're writing tests for Supabase, check out supabase-test for Supabase-optimized defaults.
pgpm migrations
Part of the pgpm ecosystem, pgsql-test is built to pair seamlessly with our TypeScript-based package manager and migration tool. pgpm gives you modular Postgres packages, deterministic plans, and tag-aware releases—perfect for authoring the migrations that pgsql-test runs.
Table of Contents
- Install
- Features
- Quick Start
getConnections() Overview
- PgTestClient API Overview
- Usage Examples
- Basic Setup
- Role-Based Context
- Seeding System
- SQL File Seeding
- Programmatic Seeding
- CSV Seeding
- JSON Seeding
- pgpm Seeding
getConnections() Options
- Disclaimer
✨ Quick Start
import { getConnections } from 'pgsql-test';
let db, teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections());
await db.query(`SELECT 1`); // ✅ Ready to run queries
});
afterAll(() => teardown());
getConnections() Overview
import { getConnections } from 'pgsql-test';
// Complete object destructuring
const { pg, db, admin, teardown, manager } = await getConnections();
// Most common pattern
const { db, teardown } = await getConnections();
The getConnections() helper sets up a fresh PostgreSQL test database and returns a structured object with:
pg: a PgTestClient connected as the root or superuser — useful for administrative setup or introspection
db: a PgTestClient connected as the app-level user — used for running tests with RLS and granted permissions
admin: a DbAdmin utility for managing database state, extensions, roles, and templates
teardown(): a function that shuts down the test environment and database pool
manager: a shared connection pool manager (PgTestConnector) behind both clients
Together, these allow fast, isolated, role-aware test environments with per-test rollback and full control over setup and teardown.
The PgTestClient returned by getConnections() is a fully-featured wrapper around pg.Pool. It provides:
- Automatic transaction and savepoint management for test isolation
- Easy switching of role-based contexts for RLS testing
- A clean, high-level API for integration testing PostgreSQL systems
PgTestClient API Overview
let pg: PgTestClient;
let teardown: () => Promise<void>;
beforeAll(async () => {
({ pg, teardown } = await getConnections());
});
beforeEach(() => pg.beforeEach());
afterEach(() => pg.afterEach());
afterAll(() => teardown());
The PgTestClient returned by getConnections() wraps a pg.Client and provides convenient helpers for query execution, test isolation, and context switching.
Common Methods
query(sql, values?) – Run a raw SQL query and get the QueryResult
beforeEach() – Begins a transaction and sets a savepoint (called at the start of each test)
afterEach() – Rolls back to the savepoint and commits the outer transaction (cleans up test state)
setContext({ key: value }) – Sets PostgreSQL config variables (like role) to simulate RLS contexts
expectError(run, expected?) – Asserts run fails (message substring/RegExp, or { code, message }) inside a savepoint, so the transaction stays usable afterwards; resolves to the caught error (see Expected failures)
checkConstraints() – Runs the commit-time checks for any pending deferred constraints now, without committing (see Deferred constraints)
any, one, oneOrNone, many, manyOrNone, none, result – Typed query helpers for specific result expectations
These methods make it easier to build expressive and isolated integration tests with strong typing and error handling.
The PgTestClient returned by getConnections() is a fully-featured wrapper around pg.Pool. It provides:
- Automatic transaction and savepoint management for test isolation
- Easy switching of role-based contexts for RLS testing
- A clean, high-level API for integration testing PostgreSQL systems
Usage Examples
⚡ Basic Setup
import { getConnections } from 'pgsql-test';
let db; // A fully wrapped PgTestClient using pg.Pool with savepoint-based rollback per test
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections());
await db.query(`
CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT);
CREATE TABLE posts (id SERIAL PRIMARY KEY, user_id INT REFERENCES users(id), content TEXT);
INSERT INTO users (name) VALUES ('Alice'), ('Bob');
INSERT INTO posts (user_id, content) VALUES (1, 'Hello world!'), (2, 'Graphile is cool!');
`);
});
afterAll(() => teardown());
beforeEach(() => db.beforeEach());
afterEach(() => db.afterEach());
test('user count starts at 2', async () => {
const res = await db.query('SELECT COUNT(*) FROM users');
expect(res.rows[0].count).toBe('2');
});
🔐 Role-Based Context
The pgsql-test framework provides powerful tools to simulate authentication contexts during tests, which is particularly useful when testing Row-Level Security (RLS) policies.
Setting Test Context
Use setContext() to simulate different user roles and JWT claims:
db.setContext({
role: 'authenticated',
'jwt.claims.user_id': '123',
'jwt.claims.org_id': 'acme'
});
This applies the settings using SET LOCAL and set_config(..., true) statements, ensuring they persist only for the current transaction and maintain proper isolation between tests.
⚠️ Important: set_config(..., true) is transaction-local. Inside test bodies (it() blocks), beforeEach() has already started a transaction, so context persists across queries automatically. However, in beforeAll() there is no active transaction — each query runs in auto-commit mode and context is lost between calls. If you need context-aware operations in beforeAll(), wrap them in explicit db.begin() / db.commit():
beforeAll(async () => {
({ db, teardown } = await getConnections());
await db.begin();
db.setContext({ role: 'authenticated', 'jwt.claims.user_id': '123' });
await db.query('SELECT current_user_id()'); // context persists within transaction
await db.commit();
});
Testing Role-Based Access
describe('authenticated role', () => {
beforeEach(async () => {
db.setContext({ role: 'authenticated' });
await db.beforeEach();
});
afterEach(() => db.afterEach());
it('runs as authenticated', async () => {
const res = await db.query(`SELECT current_setting('role', true) AS role`);
expect(res.rows[0].role).toBe('authenticated');
});
});
Database Connection Options
For non-superuser testing, use the connection options described in the options section. The db.connection property allows you to customize the non-privileged user account for your tests.
Use setContext() to simulate Role-Based Access Control (RBAC) during tests. This is useful when testing Row-Level Security (RLS) policies. Your actual server should manage role/user claims via secure tokens (e.g., setting current_setting('jwt.claims.user_id')), but this interface helps emulate those behaviors in test environments.
Common Testing Scenarios
This approach enables testing various access patterns:
- Authenticated vs. anonymous user access
- Per-user data filtering
- Admin privilege bypass behavior
- Custom claim-based restrictions (organization membership, admin status)
Note: While this interface helps simulate RBAC for testing, your production server should manage user/role claims via secure authentication tokens, typically by setting values like current_setting('jwt.claims.user_id') through proper authentication middleware.
🌱 Seeding System
The second argument to getConnections() is an optional array of SeedAdapter objects:
const { db, teardown } = await getConnections(getConnectionOptions, seedAdapters);
This array lets you fully customize how your test database is seeded. You can compose multiple strategies:
seed.sqlfile() – Execute raw .sql files from disk
seed.fn() – Run JavaScript/TypeScript logic to programmatically insert data
seed.csv() – Load tabular data from CSV files
seed.json() – Use in-memory objects as seed data
seed.pgpm() – Apply a pgpm project or set of packages (compatible with sqitch)
✨ Default Behavior: If no SeedAdapter[] is passed, pgpm seeding is assumed. This makes pgsql-test zero-config for pgpm-based projects.
This composable system allows you to mix-and-match data setup strategies for flexible, realistic, and fast database tests.
Shared fixtures survive per-test rollbacks
Seed adapters run once, before any test, and are committed. beforeEach() then opens a transaction and a savepoint, and afterEach() rolls back to it, so every test starts from the seeded state no matter what the previous test changed:
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
seed.sqlfile([sql('schema.sql')]),
seed.json({ users: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }] })
]));
});
beforeEach(() => db.beforeEach());
afterEach(() => db.afterEach());
it('can delete everything', async () => {
await db.query('DELETE FROM users');
});
it('still sees the fixtures', async () => {
expect((await db.one('SELECT count(*) FROM users')).count).toBe('2');
});
For fixtures shared by one describe block only, open a transaction and a named savepoint in its beforeAll, seed, give each test its own inner savepoint, and roll the block back in afterAll. Jest runs outer hooks for nested tests too, so keep the file-level beforeEach()/afterEach() in a sibling describe rather than around this block:
describe('with an extra admin', () => {
beforeAll(async () => {
await db.begin();
await db.query(`INSERT INTO users VALUES (99, 'Admin')`);
await db.savepoint('group');
});
afterAll(async () => {
await db.rollback('group');
await db.query('ROLLBACK');
});
beforeEach(() => db.savepoint('test'));
afterEach(() => db.rollback('test'));
// tests here see Alice, Bob and Admin; the next block sees Alice and Bob
});
To make the whole per-file setup cheap too, point db.template (or PGTEMPLATE) at a database that already has your schema: each test database is then cloned from it instead of re-deployed.
Two Seeding Patterns
You can seed data using either approach:
1. Adapter Pattern (setup phase via getConnections)
const { db, teardown } = await getConnections({}, [
seed.json({ 'users': [{ id: 1, name: 'Alice' }] })
]);
2. Direct Load Methods (runtime via PgTestClient)
await db.loadJson({ 'users': [{ id: 1, name: 'Alice' }] });
await db.loadCsv({ 'users': '/path/to/users.csv' });
await db.loadSql(['/path/to/schema.sql']);
Note: loadCsv() and loadPgpm() do not apply RLS context (PostgreSQL limitation). Use loadJson() or loadSql() for RLS-aware seeding.
🔌 SQL File Seeding
Adapter Pattern:
const { db, teardown } = await getConnections({}, [
seed.sqlfile(['schema.sql', 'fixtures.sql'])
]);
Direct Load Method:
await db.loadSql(['schema.sql', 'fixtures.sql']);
import path from 'path';
import { getConnections, seed } from 'pgsql-test';
const sql = (f: string) => path.join(__dirname, 'sql', f);
let db;
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
seed.sqlfile([
sql('schema.sql'),
sql('fixtures.sql')
])
]));
});
afterAll(async () => {
await teardown();
});
🧠 Programmatic Seeding
Adapter Pattern:
const { db, teardown } = await getConnections({}, [
seed.fn(async ({ pg }) => {
await pg.query(`INSERT INTO users (name) VALUES ('Seeded User')`);
})
]);
Direct Load Method:
// Use any PgTestClient method directly
await db.query(`INSERT INTO users (name) VALUES ('Seeded User')`);
import { getConnections, seed } from 'pgsql-test';
let db;
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
seed.fn(async ({ pg }) => {
await pg.query(`
INSERT INTO users (name) VALUES ('Seeded User');
`);
})
]));
});
🗃️ CSV Seeding
Adapter Pattern:
const { db, teardown } = await getConnections({}, [
seed.csv({
'users': '/path/to/users.csv',
'posts': '/path/to/posts.csv'
})
]);
Direct Load Method:
await db.loadCsv({
'users': '/path/to/users.csv',
'posts': '/path/to/posts.csv'
});
Note: CSV loading uses PostgreSQL COPY which does not support RLS context.
You can load tables from CSV files using seed.csv({ ... }). CSV headers must match the table column names exactly. This is useful for loading stable fixture data for integration tests or CI environments.
import path from 'path';
import { getConnections, seed } from 'pgsql-test';
const csv = (file: string) => path.resolve(__dirname, '../csv', file);
let db;
let teardown;
beforeAll(async () => {
({ db, teardown } = await getConnections({}, [
// Create schema
seed.fn(async ({ pg }) => {
await pg.query(`
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
user_id INT REFERENCES users(id),
content TEXT NOT NULL
);
`);
}),
// Load from CSV
seed.csv({
users: csv('users.csv'),
posts: csv('posts.csv')
}),
// Adjust SERIAL sequences to avoid conflicts
seed.fn(async ({ pg }) => {
await pg.query(`SELECT setval(pg_get_serial_sequence('users', 'id'), (SELECT MAX(id) FROM users));`);
await pg.query(`SELECT setval(pg_get_serial_sequence('posts', 'id'), (SELECT MAX(id) FROM posts));`);
})
]));
});
afterAll(() => teardown());
it('has loaded rows', async () => {
const res = await db.query('SELECT COUNT(*) FROM users');
expect(+res.rows[0].count).toBeGreaterThan(0);
});
🗃️ JSON Seeding
Adapter Pattern:
const { db, teardown } = await getConnections({}, [
seed.json({
'custom.users': [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
})
]);
Direct Load Method:
await db.loadJson({
'custom.users': [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
});
You can seed tables using in-memory JSON objects. This is useful when you want fast, inline fixtures without managing external files.