{"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,"search_vec":"'2.1.7':78 'activ':83 'allow':40 'appear':80 'applic':20,122 'basic':61 'behav':110 'cadenc':89 'chang':119 'code':123 'complex':69 'connect':16,109,116 'core':95 'current':75 'custom':73 'data':56 'databas':15 'defin':45 'design':11 'develop':41 'differenti':96 'direct':100 'ensur':106 'expect':50 'explicit':92 'function':74 'ident':112 'includ':52 'instanc':38 'integr':101 'interfac':105 'isn':90 'javascript':7,126 'librari':3,10,58 'lie':97 'logic':71 'maintain':84 'mechan':32 'minim':118 'mock':2,13,108,130 'near':111 'need':120 'npm':27 'packag':28 'paramet':66 'pg':26,104,115,127 'pg.client':35 'pg.pool':37 'pgmock2':4 'popular':25 'postgr':128 'postgresql':1,14,129 'pre':44 'pre-defin':43 'primarili':17 'provid':30 'queri':47,65 'real':114 'releas':88 'reli':22 'respons':51 'row':55 'rowcount':53 'simul':34 'specif':87 'sql':46 'state':93 'support':59 'test':19,125,131,132 'therebi':117 'though':85 'type':62 'typescript':9,133 'use':72 'valid':63,70 'version':77","created_at":"2026-04-22T04:50:38.617732+00:00","updated_at":"2026-04-22T04:50:38.617732+00:00","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","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":"https://jfavrod.github.io/pgmock2/","github":"https://github.com/jfavrod/pgmock2","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/pgmock2","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-21","install_tag":null}}