pg-transactional-tests is a utility library designed to simplify database testing by wrapping each test in a PostgreSQL transaction. It currently stands at version 1.2.0, with a stable release cadence implied by its versioning and active development. The library patches the `pg` package to automatically initiate a transaction before a test, and then roll it back afterward, ensuring a clean database state for every test run without the overhead of clearing tables. A key differentiator is its compatibility with many popular ORMs like Sequelize, TypeORM, MikroORM, Objection, and Knex, which all build upon the `pg` driver. It also intelligently handles nested transactions using savepoints and supports parallel testing across multiple databases by tracking transaction state per connection. A significant limitation is its incompatibility with Prisma, due to Prisma's distinct database interaction model. This approach vastly accelerates test suites and reduces boilerplate for database setup and teardown.
npm install pg-transactional-testsVerified import paths — ran on the pinned version, not inferred.
Demonstrates the essential Jest setup to enable transactional tests for a test suite, ensuring clean database state for every test.
If using Prisma, this library cannot be used. Consider alternative testing strategies like Prisma's own `db push` for schema migrations or dedicated test databases per run.
Always test `pg-transactional-tests` thoroughly when upgrading `pg` to a new major version. Monitor the library's GitHub for compatibility updates.
Ensure `testTransaction.close` is always called in your `afterAll` hook in your test setup file.
Always pair `beforeEach(testTransaction.start)` with `afterEach(testTransaction.rollback)` to ensure proper transactional isolation for each test.
Install the 'pg' package: `npm install pg` or `yarn add pg` or `pnpm add pg`.
Ensure you are using `import { testTransaction } from 'pg-transactional-tests';` and that your environment supports ES Modules, or configure your bundler/test runner (like Jest) to handle module resolution correctly.Add `afterAll(testTransaction.close);` to your test setup file (e.g., `jest-setup.ts`).
Add `afterEach(testTransaction.rollback);` to your test setup file to ensure each test runs in isolation.