PostgreSQL Mocking Library
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.
Common errors
-
Error: Query not found.
cause The executed query string (after normalization) does not match any queries previously added with `pg.add()`.fixVerify 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.
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()`.fixEnsure 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.
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()`.fixReview 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`).
Warnings
- gotcha 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install pgmock2 -
yarn add pgmock2 -
pnpm add pgmock2
Imports
- PgMock2
const PgMock2 = require('pgmock2');import PgMock2 from 'pgmock2';
- PgMock2Client
import PgMock2, { PgMock2Client } from 'pgmock2'; // Or for the instance: const client = new PgMock2(); - QueryConfig
import { QueryConfig } from 'pgmock2';import type { QueryConfig } from 'pgmock2';
Quickstart
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);
}
})();