PostgreSQL Mocking Library

2.1.7 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

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);
    }
})();

view raw JSON →