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-testVerified import paths — ran on the pinned version, not inferred.
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.
Review the package's GitHub releases or changelog for detailed migration instructions before upgrading major versions.
Ensure `await teardown();` is called in an `afterAll` or `after` hook to properly clean up the test database.
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.
Optimize seeding by loading only necessary data, using smaller datasets for unit-level integration tests, or leveraging `pgpm` for efficient, incremental migrations where applicable.
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.
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.
Install the `pg` package as a dependency: `npm install pg` or `yarn add pg`.
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.