{"id":13765,"library":"pg-transactional-tests","title":"PostgreSQL Transactional Tests","description":"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.","status":"active","version":"1.2.0","language":"javascript","source_language":"en","source_url":"https://github.com/romeerez/pg-transactional-tests","tags":["javascript","pg","postgres","transactional tests","test","typescript"],"install":[{"cmd":"npm install pg-transactional-tests","lang":"bash","label":"npm"},{"cmd":"yarn add pg-transactional-tests","lang":"bash","label":"yarn"},{"cmd":"pnpm add pg-transactional-tests","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"The library patches and relies on the 'pg' client for database interactions. It is a peer dependency.","package":"pg","optional":false}],"imports":[{"note":"The library primarily uses ES modules; CommonJS `require` might lead to issues in mixed environments or older Node.js setups without proper transpilation.","wrong":"const { testTransaction } = require('pg-transactional-tests');","symbol":"testTransaction","correct":"import { testTransaction } from 'pg-transactional-tests';"},{"note":"Used as a hook in testing frameworks to begin a transaction for each test.","symbol":"testTransaction.start","correct":"beforeEach(testTransaction.start);"},{"note":"Used as a hook to roll back the transaction after each test, ensuring database isolation.","symbol":"testTransaction.rollback","correct":"afterEach(testTransaction.rollback);"},{"note":"Used as a hook to close all `pg` connections opened by the transactional tests, preventing resource leaks.","symbol":"testTransaction.close","correct":"afterAll(testTransaction.close);"}],"quickstart":{"code":"import { testTransaction } from 'pg-transactional-tests';\n\n// This setup file should be configured in your test runner, e.g., Jest's `setupFilesAfterEnv`.\n// It ensures that every test involving the database runs within its own transaction\n// and that the transaction is rolled back afterwards.\n\n// Starts a transaction before any tests begin (useful if using `beforeAll` hooks that perform queries)\nbeforeAll(testTransaction.start);\n\n// Starts a new savepoint/transaction before each individual test\nbeforeEach(testTransaction.start);\n\n// Rolls back the transaction/savepoint after each test completes, ensuring isolation\nafterEach(testTransaction.rollback);\n\n// Closes all PostgreSQL connections managed by pg-transactional-tests after all tests are done\nafterAll(testTransaction.close);\n\n// Example test structure for context:\n// describe('User Service', () => {\n//   it('should create a user', async () => {\n//     // Your ORM or pg client code here will run inside a transaction\n//     await someORM.user.create({ name: 'Test User' });\n//     const user = await someORM.user.findUnique({ where: { name: 'Test User' } });\n//     expect(user).not.toBeNull();\n//   });\n//   it('should not persist user across tests', async () => {\n//     const count = await someORM.user.count();\n//     expect(count).toBe(0); // Because previous test's transaction was rolled back\n//   });\n// });","lang":"typescript","description":"Demonstrates the essential Jest setup to enable transactional tests for a test suite, ensuring clean database state for every test."},"warnings":[{"fix":"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.","message":"This library is fundamentally incompatible with Prisma ORM due to Prisma's unique database interaction model, which does not utilize the standard `pg` client in a way that allows for the library's patching mechanism to function correctly.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Always test `pg-transactional-tests` thoroughly when upgrading `pg` to a new major version. Monitor the library's GitHub for compatibility updates.","message":"The library works by patching the underlying `pg` package. This creates a dependency on `pg`'s internal implementation details, which could potentially break with future major versions of `pg` if its internal structure changes significantly.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure `testTransaction.close` is always called in your `afterAll` hook in your test setup file.","message":"Failing to call `afterAll(testTransaction.close)` will leave database connections open after your test suite completes, potentially leading to resource exhaustion or preventing your test runner from exiting cleanly.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always pair `beforeEach(testTransaction.start)` with `afterEach(testTransaction.rollback)` to ensure proper transactional isolation for each test.","message":"If `testTransaction.rollback` is not called after `testTransaction.start` for each test, database changes will persist, leading to flaky and interdependent tests. This often happens if only `beforeAll` is used instead of `beforeEach` and `afterEach`.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'1.2.0':30 'acceler':142 'across':114 'activ':41 'afterward':62 'also':103 'approach':140 'automat':50 'back':61 'boilerpl':147 'build':97 'cadenc':35 'clean':65 'clear':76 'compat':83 'connect':122 'current':26 'databas':15,66,116,136,149 'design':12 'develop':42 'differenti':80 'distinct':135 'driver':101 'due':131 'ensur':63 'everi':69 'handl':105 'impli':36 'incompat':128 'initi':51 'intellig':104 'interact':137 'javascript':153 'key':79 'knex':94 'librari':11,44 'like':88 'limit':125 'mani':85 'mikroorm':91 'model':138 'multipl':115 'nest':106 'object':92 'orm':87 'overhead':74 'packag':48 'parallel':112 'patch':45 'per':121 'pg':5,47,100,154 'pg-transactional-test':4 'popular':86 'postgr':155 'postgresql':1,23 'prisma':130,133 'reduc':146 'releas':34 'roll':59 'run':71 'savepoint':109 'sequel':89 'setup':150 'signific':124 'simplifi':14 'stabl':33 'stand':27 'state':67,120 'suit':144 'support':111 'tabl':77 'teardown':152 'test':3,7,16,20,56,70,113,143,157,158 'track':118 'transact':2,6,24,53,107,119,156 'typeorm':90 'typescript':159 'upon':98 'use':108 'util':10 'vast':141 'version':29,39 'without':72 'wrap':18","created_at":"2026-04-20T01:56:11.764680+00:00","updated_at":"2026-04-20T01:56:11.764680+00:00","problems":[{"fix":"Install the 'pg' package: `npm install pg` or `yarn add pg` or `pnpm add pg`.","cause":"The 'pg' package is a peer dependency but has not been installed in your project.","error":"Error: Cannot find module 'pg'"},{"fix":"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.","cause":"The `testTransaction` object was not correctly imported or is being accessed before it's initialized (e.g., in a pure CommonJS environment without proper transpilation/config).","error":"TypeError: Cannot read properties of undefined (reading 'start') or 'rollback' or 'close'"},{"fix":"Add `afterAll(testTransaction.close);` to your test setup file (e.g., `jest-setup.ts`).","cause":"The `testTransaction.close()` function was not called in the `afterAll` hook of your test setup.","error":"Tests fail due to too many open connections or hanging processes after tests run."},{"fix":"Add `afterEach(testTransaction.rollback);` to your test setup file to ensure each test runs in isolation.","cause":"The `testTransaction.rollback()` function was not called in the `afterEach` hook of your test setup.","error":"Test data persists between individual tests, making tests interdependent and flaky."}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/romeerez/pg-transactional-tests","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/pg-transactional-tests","openapi_spec":null,"status_page":null,"smithery":null,"categories":["testing","database"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}