Registry / testing / pgmock2

pgmock2

JSON →
library2.1.7jsnpmunverified

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 pgmock2
INSTALL
IMPORT
SIG · PGMOCK2
P
pgmock2
testingjavascriptv2.1.7
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PgMock2
import PgMock2 from 'pgmock2';
const PgMock2 = require('pgmock2');
While `require('pgmock2').default` works, the direct `import` is preferred for ESM contexts. For CJS, `require('pgmock2')` directly returns the default export.
PgMock2Client
import PgMock2, { PgMock2Client } from 'pgmock2'; // Or for the instance: const client = new PgMock2();
PgMock2Client is the type returned by `pg.connect()`. The primary export is the PgMock2 class itself.
QueryConfig
import type { QueryConfig } from 'pgmock2';
import { QueryConfig } from 'pgmock2';
Use `import type` when only importing types to ensure it's removed during transpilation and doesn't affect runtime.

This quickstart demonstrates how to set up mock queries with `pgmock2`, including parameter validation, and then execute those queries against a mock client.

import PgMock2 from 'pgmock2'; const pg = new PgMock2(); // Add a query with a number validation for the first parameter ($1) pg.add('SELECT * FROM employees WHERE id=$1', ['number'], { rowCount: 1, rows: [ { id: 1, name: 'John Smith', position: 'application developer' } ] }); // Add a query without parameters pg.add('SELECT * FROM products', [], { rowCount: 2, rows: [ { id: 101, name: 'Laptop', price: 1200 }, { id: 102, name: 'Mouse', price: 25 } ] }); (async function() { try { // Connect to the mock database const client = await pg.connect(); // Query with a valid parameter const employeeData = await client.query('SELECT * FROM employees WHERE id=$1;', [1]); console.log('Employee Query Result:', employeeData.rows); // Query without parameters const productData = await client.query('SELECT * FROM products;'); console.log('Product Query Result:', productData.rows); // Attempt a query with an invalid parameter type (will likely throw) await client.query('SELECT * FROM employees WHERE id=$1;', ['invalid']); } catch (err: any) { console.error('Error during quickstart:', err.message); } })();
Debug
Known issues
gotchapgmock2 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.
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.
affects: >=1.0.0
gotchaThe 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.
fix
Always provide a response object with at least `rowCount: number` and `rows: any[]`. For example: `{ rowCount: 0, rows: [] }` for an empty result.
affects: >=1.0.0
gotchaValue 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.
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.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Query not found.
The executed query string (after normalization) does not match any queries previously added with `pg.add()`.
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.
Error: Invalid number of values provided. Expected X, got Y.
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()`.
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.
Error: Value at index X failed validation.
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()`.
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`).
Upgrade
Version history
2.1.7latest on npm
Audit
Dependencies
pgoptionalpgmock2 mocks connections and interfaces from the `pg` package; applications using pgmock2 will typically have `pg` as a direct dependency.
Agent activity
4 hits · last 30 days
node
4
Resources
pgmock2 — npm install pgmock2 · libregistry