pgmock2 is a JavaScript and TypeScript library designed for mocking PostgreSQL database connections, primarily for testing applications that rely on the popular `pg` npm package. It provides a mechanism to simulate `pg.Client` and `pg.Pool` instances by allowing developers to pre-define SQL queries and their expected responses, including `rowCount` and `rows` data. The library supports both basic type validation for query parameters and more complex validation logic using custom functions. Currently at version 2.1.7, it appears to be actively maintained, though a specific release cadence isn't explicitly stated. Its core differentiation lies in its direct integration with the `pg` interface, ensuring that mocked connections behave nearly identically to real `pg` connections, thereby minimizing changes needed in application code during testing.
npm install pgmock2Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up mock queries with `pgmock2`, including parameter validation, and then execute those queries against a mock client.
Be aware of the normalization behavior; ensure your `add` calls define queries that match the expected normalized form, or rely on the normalization for flexibility. Avoid overly specific whitespace/casing in your test query strings.
Always provide a response object with at least `rowCount: number` and `rows: any[]`. For example: `{ rowCount: 0, rows: [] }` for an empty result.Ensure the values provided in the `query` method's second parameter precisely match the validation rules defined when adding the query. For custom functions, verify the function returns `true` for valid inputs.
Verify that the query string in `client.query()` exactly matches (after considering normalization) one of the queries added via `pg.add()`. Check for typos or unexpected parameter binding syntax.
Ensure the array of values passed to `client.query()` has the same length as the array of validation rules provided to `pg.add()` for that specific query.
Review the validation rule for the specified index in `pg.add()` and confirm the value provided in `client.query()` meets that criteria (e.g., correct `typeof` or the custom validation function returns `true`).