Registry / testing / pgsql-test

pgsql-test

JSON →
library0.2.0jsnpmunverified

pgsql-test is a Node.js and TypeScript library, currently at version 4.9.1, that provides instant, isolated, and role-aware PostgreSQL databases for integration testing. It differentiates itself by ensuring each test runs within its own transaction or savepoint, which offers complete isolation, automatic rollbacks, and clean state management without polluting external database environments. Key features include support for testing Row-Level Security (RLS) via `setContext()`, flexible data seeding options (including SQL files, programmatic seeds, and integration with `pgpm` modules), and automatic teardown to prevent resource leaks. The library is actively maintained within the `constructive-io` ecosystem and is designed to be compatible with popular asynchronous test runners like Jest and Mocha, offering a reliable solution for fast and realistic database integration tests.

npm install pgsql-test
INSTALL
IMPORT
SIG · PGSQL-TEST
P
pgsql-test
testingjavascriptv0.2.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

getConnections
import { getConnections } from 'pgsql-test';
const { getConnections } = require('pgsql-test');
This is the primary named export to obtain database connections and a teardown function. It's an async function.
seed
import { seed } from 'pgsql-test';
import seed from 'pgsql-test/seed';
Provides utilities for flexible database seeding, often used with .sql files or pgpm modules. It's a named export.
setContext
import { setContext } from 'pgsql-test';
import { setContext } from 'pgsql-test/context';
Used for simulating different user roles and JWT claims, essential for testing Row-Level Security (RLS) policies.

This quickstart demonstrates setting up an isolated PostgreSQL database for a Jest/Mocha test suite, performing per-test transaction rollbacks, and running basic CRUD operations. It uses `getConnections` to manage the database lifecycle and a `pg` client for interactions.

import { getConnections } from 'pgsql-test'; import { Client } from 'pg'; describe('User Service Integration', () => { let db: Client; let teardown: () => Promise<void>; // Before all tests, set up a new isolated test database beforeAll(async () => { // getConnections creates a new UUID-named database, applies migrations // (if pgpm modules are configured), and returns a pg client and teardown function. ({ db, teardown } = await getConnections({ database: 'my_app_test', connectionString: process.env.DATABASE_URL ?? 'postgres://user:password@localhost:5432/postgres' })); // Example: Create a simple table and insert some initial data await db.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL ); `); await db.query(` INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'), ('Bob', 'bob@example.com'); `); }); // After all tests in this suite, clean up the test database afterAll(async () => { await teardown(); }); // Each test runs within its own transaction for further isolation beforeEach(async () => { await db.query('BEGIN;'); }); afterEach(async () => { await db.query('ROLLBACK;'); // Rollback all changes made in the test }); test('should retrieve all users', async () => { const res = await db.query('SELECT * FROM users ORDER BY id;'); expect(res.rows).toHaveLength(2); expect(res.rows[0].name).toBe('Alice'); }); test('should add a new user', async () => { await db.query("INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@example.com');"); const res = await db.query('SELECT * FROM users;'); expect(res.rows).toHaveLength(3); expect(res.rows.some(u => u.name === 'Charlie')).toBe(true); }); test('should not allow duplicate emails', async () => { await db.query("INSERT INTO users (name, email) VALUES ('David', 'david@example.com');"); await expect(db.query("INSERT INTO users (name, email) VALUES ('Eve', 'david@example.com');")).rejects.toThrow(/duplicate key value violates unique constraint/); }); });
Debug
Known issues
breakingMajor version updates (e.g., from v3 to v4) in pgsql-test or its underlying `constructive-io` dependencies may introduce breaking API changes. Always consult the release notes and migration guides for the specific version you are upgrading to.
fix
Review the package's GitHub releases or changelog for detailed migration instructions before upgrading major versions.
affects: >=3.0.0
gotchaFailing to call the `teardown()` function returned by `getConnections()` can leave test databases active after tests complete. This leads to resource consumption and potential conflicts in subsequent test runs, especially in CI/CD environments.
fix
Ensure `await teardown();` is called in an `afterAll` or `after` hook to properly clean up the test database.
affects: >=1.0.0
gotchapgsql-test relies on an accessible PostgreSQL server (e.g., via Docker or a local instance) to create and manage test databases. If the PostgreSQL server is not running or misconfigured, `getConnections()` will fail.
fix
Verify your PostgreSQL server is running and accessible from where your tests are executed. Ensure connection details (host, port, user, password) are correctly provided, often via environment variables.
affects: >=1.0.0
gotchaExtensive or complex seeding operations (e.g., loading large datasets, running many SQL migration files) can significantly increase test setup time, particularly when using per-test isolation or frequent database recreation.
fix
Optimize seeding by loading only necessary data, using smaller datasets for unit-level integration tests, or leveraging `pgpm` for efficient, incremental migrations where applicable.
affects: >=1.0.0
Errors
Common errors & fixes
error: password authentication failed for user "testuser"
The PostgreSQL connection string provided has incorrect credentials for the specified user.
fix
Double-check the username and password in your connection string (e.g., `DATABASE_URL` environment variable) and ensure the PostgreSQL user has access to create/manage databases.
psql: error: could not connect to server: Connection refused
The PostgreSQL server is not running, or it's not accessible at the specified host and port.
fix
Ensure your PostgreSQL server is started and listening on the correct host/port. If using Docker, verify the container is running and ports are mapped correctly.
Error: Cannot find module 'pg'
Although pgsql-test manages connections, the `db` client returned by `getConnections()` is an instance of `pg.Client`. If your application code uses the `pg` client directly, it must be installed.
fix
Install the `pg` package as a dependency: `npm install pg` or `yarn add pg`.
ERROR: database "uuid-xyz-test" already exists
A previous test run failed to clean up the temporary database, or multiple parallel tests are attempting to create the same UUID-named database due to a bug or misconfiguration.
fix
Ensure `teardown()` is reliably called in `afterAll`. If the issue persists with parallel tests, review your test runner's concurrency settings or pgsql-test's configuration for unique database naming.
Upgrade
Version history
0.2.0latest on npm
Audit
Dependencies
pgrequiredWhile pgsql-test provides database connections, applications typically interact with PostgreSQL using the 'pg' client library. This is a common peer dependency for application logic.
Agent activity
4 hits · last 30 days
node
4
Resources