{"id":16486,"library":"pgmock2","title":"PostgreSQL Mocking Library","description":"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.","status":"active","version":"2.1.7","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/jfavrod/pgmock2","tags":["javascript","pg","postgres","postgresql","mock","test","testing","typescript"],"install":[{"cmd":"npm install pgmock2","lang":"bash","label":"npm"},{"cmd":"yarn add pgmock2","lang":"bash","label":"yarn"},{"cmd":"pnpm add pgmock2","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"pgmock2 mocks connections and interfaces from the `pg` package; applications using pgmock2 will typically have `pg` as a direct dependency.","package":"pg","optional":true}],"imports":[{"note":"While `require('pgmock2').default` works, the direct `import` is preferred for ESM contexts. For CJS, `require('pgmock2')` directly returns the default export.","wrong":"const PgMock2 = require('pgmock2');","symbol":"PgMock2","correct":"import PgMock2 from 'pgmock2';"},{"note":"PgMock2Client is the type returned by `pg.connect()`. The primary export is the PgMock2 class itself.","symbol":"PgMock2Client","correct":"import PgMock2, { PgMock2Client } from 'pgmock2';\n// Or for the instance:\nconst client = new PgMock2();"},{"note":"Use `import type` when only importing types to ensure it's removed during transpilation and doesn't affect runtime.","wrong":"import { QueryConfig } from 'pgmock2';","symbol":"QueryConfig","correct":"import type { QueryConfig } from 'pgmock2';"}],"quickstart":{"code":"import PgMock2 from 'pgmock2';\n\nconst pg = new PgMock2();\n\n// Add a query with a number validation for the first parameter ($1)\npg.add('SELECT * FROM employees WHERE id=$1', ['number'], {\n    rowCount: 1,\n    rows: [\n        { id: 1, name: 'John Smith', position: 'application developer' }\n    ]\n});\n\n// Add a query without parameters\npg.add('SELECT * FROM products', [], {\n    rowCount: 2,\n    rows: [\n        { id: 101, name: 'Laptop', price: 1200 },\n        { id: 102, name: 'Mouse', price: 25 }\n    ]\n});\n\n(async function() {\n    try {\n        // Connect to the mock database\n        const client = await pg.connect();\n\n        // Query with a valid parameter\n        const employeeData = await client.query('SELECT * FROM employees WHERE id=$1;', [1]);\n        console.log('Employee Query Result:', employeeData.rows);\n\n        // Query without parameters\n        const productData = await client.query('SELECT * FROM products;');\n        console.log('Product Query Result:', productData.rows);\n\n        // Attempt a query with an invalid parameter type (will likely throw)\n        await client.query('SELECT * FROM employees WHERE id=$1;', ['invalid']);\n    } catch (err: any) {\n        console.error('Error during quickstart:', err.message);\n    }\n})();","lang":"typescript","description":"This quickstart demonstrates how to set up mock queries with `pgmock2`, including parameter validation, and then execute those queries against a mock client."},"warnings":[{"fix":"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.","message":"pgmock2 normalizes SQL queries internally by disregarding whitespace and making them case-insensitive. This means the query string provided to `add` and `query` does not need to be an exact match, but users expecting strict string comparisons might encounter unexpected matches or mismatches.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always provide a response object with at least `rowCount: number` and `rows: any[]`. For example: `{ rowCount: 0, rows: [] }` for an empty result.","message":"The third parameter to the `add` method, which defines the query response, MUST strictly adhere to the `pg.QueryResponse` interface (i.e., contain `rowCount` and `rows` properties). Missing or incorrectly typed properties will lead to runtime errors when the mock query is executed.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"Value validation in `add` uses either `typeof` strings (e.g., 'number', 'string') or custom functions. Mismatches between the validation rules defined in `add` and the actual values passed to `query` will result in an error being thrown.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"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.","cause":"The executed query string (after normalization) does not match any queries previously added with `pg.add()`.","error":"Error: Query not found."},{"fix":"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.","cause":"The number of values provided in the second argument of `client.query()` does not match the number of validation rules (second argument) provided during `pg.add()`.","error":"Error: Invalid number of values provided. Expected X, got Y."},{"fix":"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`).","cause":"A value passed to `client.query()` did not pass the validation rule (type string or custom function) defined for its corresponding index in `pg.add()`.","error":"Error: Value at index X failed validation."}],"ecosystem":"npm"}