Mankind1023
Mankind1023

Reputation: 7752

Node / Sinon - Stub function in library or module (node-postgres)

I'm trying to test a function that queries the database using pg module, here is how I'm using it:

const { Pool } = require('pg');
const { liveDB } = require('../config/db');
const pool = new Pool(liveDB);

exports.query = async (query) => {
    const client = await pool.connect();

    try {
        var result = await client.query(query);
        console.log('result from db.query', result);
        return result;
    } catch (err) {
        console.log('ERROR in db.query')
        console.error(err);
        throw err;
    } finally {
        console.log('Releasing client');
        await client.release();
    }
};

Normally, I would stub a function like this (db.saveUser is a fake function here, but it does get stubbed correctly):

var stub = sinon.stub(db, 'saveUser').callsFake(() => { return 'Saved from stub' });

This however, is not working on the pg module, I tried stubbing the constructor, Pool, .connect, .release and even the entire module, but nothing seems to work for some reason.

PS: I tried changing const to var on all variables as well because I thought it was the cause, same results. I also tried promises in the stub, in several ways, no change.

Upvotes: 2

Views: 1366

Answers (1)

alexmac
alexmac

Reputation: 19627

Create a new function which returns a pg client and use it in query function:

// db.js

exports.getPgClient = () => {
  return pool.connect();
};

exports.query = async (query) => {
  const client = await exports.getPgClient();
  ...
};

In your test, create a stub for getPgClient function and return a fake client with stubbed connect and release methods:

// test.js

let fakeClient = {
  connect() => { do something or stub this method },
  release() => { do something or stub this method }
};

before() => {
  sinon.stub(db, 'getPgClient').callsFake(() => Promise.resolve(fakeClient));
});

Note: I return a fulfilled promise in stubbed getPgClient function, because original function returns a Promise too.

Upvotes: 1

Related Questions