insforge-test
v1.20.5
Published
insforge-test offers isolated, role-aware, and rollback-friendly PostgreSQL environments for integration tests with InsForge defaults baked in
Maintainers
Readme
insforge-test
insforge-test is an InsForge-optimized version of pgsql-test with InsForge defaults baked in. It provides instant, isolated PostgreSQL databases for testing with automatic transaction rollbacks, context switching, and clean seeding — configured for InsForge's local development environment. It's also great for GitHub Actions and CI/CD testing.
Install
npm install insforge-testFeatures
- 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
.sqlfiles, 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
Quick Start
import { getConnections } from 'insforge-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 'insforge-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: aPgTestClientconnected as the root or superuser — useful for administrative setup or introspectiondb: aPgTestClientconnected as the app-level user — used for running tests with RLS and granted permissionsadmin: aDbAdminutility for managing database state, extensions, roles, and templatesteardown(): a function that shuts down the test environment and database poolmanager: 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 theQueryResultbeforeEach()– 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 (likerole) to simulate RLS contextsany,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 'insforge-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, 'Testing InsForge!');
`);
});
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 insforge-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',
'request.jwt.claim.sub': '550e8400-e29b-41d4-a716-446655440001'
});This applies the settings using SET LOCAL statements, ensuring they persist only for the current transaction and maintain proper isolation between tests.
InsForge Roles
InsForge uses three built-in PostgreSQL roles:
| Role | Description | Use Case |
|------|-------------|----------|
| anon | Unauthenticated users | Public read access |
| authenticated | Logged-in users | Standard user operations |
| project_admin | System administrators | Full access to all resources |
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');
});
});Creating Test Users
Use insertUser() to create users in auth.users:
import { getConnections, PgTestClient, insertUser } from 'insforge-test';
let pg: PgTestClient;
let db: PgTestClient;
let teardown: () => Promise<void>;
let alice: any;
let bob: any;
beforeAll(async () => {
({ pg, db, teardown } = await getConnections());
// Create users in auth.users (requires superuser)
alice = await insertUser(pg, '[email protected]', '550e8400-e29b-41d4-a716-446655440001');
bob = await insertUser(pg, '[email protected]', '550e8400-e29b-41d4-a716-446655440002');
});Parameters:
pg- Superuser client (required for auth.users)email- User's emailid- Optional UUID (auto-generated if omitted)
Testing RLS Policies
User Can Access Own Data
it('user can insert own record', async () => {
db.setContext({
role: 'authenticated',
'request.jwt.claim.sub': alice.id
});
const result = await db.one(`
INSERT INTO public.posts (title, owner_id)
VALUES ($1, $2)
RETURNING id, title, owner_id
`, ['My Post', alice.id]);
expect(result.title).toBe('My Post');
expect(result.owner_id).toBe(alice.id);
});User Cannot Access Others' Data
it('user cannot see other users data', async () => {
// Bob creates a post
db.setContext({
role: 'authenticated',
'request.jwt.claim.sub': bob.id
});
await db.one(`
INSERT INTO public.posts (title, owner_id)
VALUES ($1, $2)
RETURNING id
`, ['Bob Post', bob.id]);
// Alice queries - should not see Bob's post
db.setContext({
role: 'authenticated',
'request.jwt.claim.sub': alice.id
});
const result = await db.query('SELECT * FROM public.posts');
expect(result.rows).toHaveLength(0);
});Testing Permission Denied
Use savepoint pattern for expected failures:
it('anonymous cannot insert', async () => {
db.setContext({ role: 'anon' });
const point = 'anon_insert';
await db.savepoint(point);
await expect(
db.query(`INSERT INTO public.posts (title) VALUES ('Hacked')`)
).rejects.toThrow(/permission denied/);
await db.rollback(point);
});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.sqlfiles from diskseed.fn()– Run JavaScript/TypeScript logic to programmatically insert dataseed.csv()– Load tabular data from CSV filesseed.json()– Use in-memory objects as seed dataseed.pgpm()– Apply a PGPM project or set of packages (compatible with sqitch)
Default Behavior: If no
SeedAdapter[]is passed, pgpm seeding is assumed. This makesinsforge-testzero-config for pgpm-based projects.
SQL File Seeding
const { db, teardown } = await getConnections({}, [
seed.sqlfile(['schema.sql', 'fixtures.sql'])
]);Programmatic Seeding
const { db, teardown } = await getConnections({}, [
seed.fn(async ({ pg }) => {
await pg.query(`INSERT INTO users (name) VALUES ('Seeded User')`);
})
]);JSON Seeding
const { db, teardown } = await getConnections({}, [
seed.json({
'public.users': [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
})
]);pgpm Seeding
// pgpm migrate is used automatically
const { db, teardown } = await getConnections();getConnections Options
db Options (PgTestConnectionOptions)
| Option | Type | Default | Description |
| ------------------------ | ---------- | ---------------- | --------------------------------------------------------------------------- |
| db.extensions | string[] | [] | Array of PostgreSQL extensions to include in the test database |
| db.cwd | string | process.cwd() | Working directory used for PGPM or Sqitch projects |
| db.connection.user | string | 'postgres' | User for simulating RLS via setContext() |
| db.connection.password | string | 'postgres' | Password for RLS test user |
| db.connection.role | string | 'anon' | Default role used during setContext() |
| db.template | string | undefined | Template database used for faster test DB creation |
| db.rootDb | string | 'postgres' | Root database used for administrative operations (e.g., creating databases) |
| db.prefix | string | 'db-' | Prefix used when generating test database names |
pg Options (PgConfig)
Environment variables will override these options when available:
PGHOST,PGPORT,PGUSER,PGPASSWORD,PGDATABASE
| Option | Type | Default | Description |
| ------------- | -------- | ------------- | ----------------------------------------------- |
| pg.user | string | 'postgres' | Superuser for PostgreSQL |
| pg.password | string | 'postgres' | Password for the PostgreSQL superuser |
| pg.host | string | 'localhost' | Hostname for PostgreSQL |
| pg.port | number | 5432 | Port for PostgreSQL |
| pg.database | string | 'postgres' | Default database used when connecting initially |
Usage
const { conn, db, teardown } = await getConnections({
pg: { user: 'postgres', password: 'secret' },
db: {
extensions: ['uuid-ossp'],
cwd: '/path/to/project',
connection: { user: 'test_user', password: 'secret', role: 'authenticated' },
template: 'test_template',
prefix: 'test_',
rootDb: 'postgres'
}
});InsForge vs Supabase Defaults
If you're coming from supabase-test, here are the key differences:
| Setting | supabase-test | insforge-test |
|---------|-----------------|-----------------|
| Admin role | service_role | project_admin |
| App user | supabase_admin | postgres |
| Default port | 54322 | 5432 |
| JWT claim key | request.jwt.claim.sub | request.jwt.claim.sub |
The anonymous (anon) and authenticated (authenticated) roles are identical across both platforms.
Snapshot Utilities
The insforge-test/utils module provides utilities for sanitizing query results for snapshot testing. These helpers replace dynamic values (IDs, UUIDs, dates, hashes) with stable placeholders, making snapshots deterministic.
import { snapshot } from 'insforge-test/utils';
const result = await db.any('SELECT * FROM users');
expect(snapshot(result)).toMatchSnapshot();See pgsql-test Snapshot Utilities for the full API reference.
Education and Tutorials
🚀 Quickstart: Getting Up and Running Get started with modular databases in minutes. Install prerequisites and deploy your first module.
📦 Modular PostgreSQL Development with Database Packages Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
✏️ Authoring Database Changes Master the workflow for adding, organizing, and managing database changes with pgpm.
🧪 End-to-End PostgreSQL Testing with TypeScript Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
⚡ Supabase Testing Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
💧 Drizzle ORM Testing Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
🔧 Troubleshooting Common issues and solutions for pgpm, PostgreSQL, and testing.
Related Constructive Tooling
📦 Package Management
- pgpm: 🖥️ PostgreSQL Package Manager for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
🧪 Testing
- pgsql-test: 📊 Isolated testing environments with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
- pglite-test: 🪶 Drop-in pgsql-test replacement backed by PGlite — in-process Postgres, no server required, instance-per-suite isolation.
- pgsql-seed: 🌱 PostgreSQL seeding utilities for CSV, JSON, SQL data loading, and pgpm deployment.
- supabase-test: 🧪 Supabase-native test harness preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
- graphile-test: 🔐 Authentication mocking for Graphile-focused test helpers and emulating row-level security contexts.
- pg-query-context: 🔒 Session context injection to add session-local context (e.g.,
SET LOCAL) into queries—ideal for settingrole,jwt.claims, and other session settings.
🧠 Parsing & AST
- pgsql-parser: 🔄 SQL conversion engine that interprets and converts PostgreSQL syntax.
- libpg-query-node: 🌉 Node.js bindings for
libpg_query, converting SQL into parse trees. - pg-proto-parser: 📦 Protobuf parser for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
- @pgsql/enums: 🏷️ TypeScript enums for PostgreSQL AST for safe and ergonomic parsing logic.
- @pgsql/types: 📝 Type definitions for PostgreSQL AST nodes in TypeScript.
- @pgsql/utils: 🛠️ AST utilities for constructing and transforming PostgreSQL syntax trees.
📚 Documentation & Skills
- constructive-skills: 📖 Platform documentation and AI agent skills — feature catalog, blueprint reference, SDK guides (i18n, billing, limits, events, uploads, security, entities, search, AI), and deployment guides.
Install skills for AI coding agents:
# All platform skills (security, blueprints, codegen, billing, etc.)
npx skills add constructive-io/constructive-skills
# Individual repo skills (pgpm, safegres, testing, CLI, search, etc.)
npx skills add constructive-io/constructive --skill pgpm
npx skills add constructive-io/constructive --skill safegres
npx skills add constructive-io/constructive --skill constructive-testingCredits
🛠 Built by the Constructive team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on GitHub.
Disclaimer
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
