Home > OS >  fake pool connection using sinon js
fake pool connection using sinon js

Time:09-22

I just want to fake pool connection and use the connection in all my unit test.

const logger = require('./logger.js');
const { Pool } = require ('pg');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
var assert = sinon.assert;

const pool = new Pool ({
    connectionString: process.env.HEROKU_POSTGRESQL_BLUE_URL,   
    ssl: {
        rejectUnauthorized: false
      },
    //max: 500      

});

async function queryWithParameter(queryToExecute,parameterReq) {
        
    var result;
    var finalResult;
    
    
    try{    
        const client = await pool.connect();
        
        try{
            if(parameterReq == null)
                result = await client.query(queryToExecute);
            else    
                result = await client.query(queryToExecute, parameterReq);  
                finalResult = result.rows;
            }
        catch(err){
            logger.error('error in queryWithParameter : '   err);
            } 
        finally{
            client.release(true);
            }
    }
    catch (err){
        
    }
    
        
    return finalResult;
}

module.exports = {
  queryWithParameter
 
};

I'm supposed to use sinon.js to fake the pool connection so I cannot hit the actual DB but failed to implement it successfully.

CodePudding user response:

I will show you how to test the test cases that "should be the correct query result".

index.js:

const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.HEROKU_POSTGRESQL_BLUE_URL,
  ssl: {
    rejectUnauthorized: false,
  },
});

async function queryWithParameter(queryToExecute, parameterReq) {
  var result;
  var finalResult;

  try {
    const client = await pool.connect();

    try {
      if (parameterReq == null) result = await client.query(queryToExecute);
      else result = await client.query(queryToExecute, parameterReq);
      finalResult = result.rows;
    } catch (err) {
      console.error('error in queryWithParameter : '   err);
    } finally {
      client.release(true);
    }
  } catch (err) {}

  return finalResult;
}

module.exports = { queryWithParameter };

index.test.js:

const sinon = require('sinon');
const proxyquire = require('proxyquire');

describe('69222273', () => {
  it('should query result', async () => {
    process.env.HEROKU_POSTGRESQL_BLUE_URL = 'whatever';
    const res = { rows: [{ message: 'Hello world!' }] };
    const clientStub = { query: sinon.stub().resolves(res), release: sinon.stub() };
    const poolStub = { connect: sinon.stub().resolves(clientStub) };
    const pgStub = { Pool: sinon.stub().returns(poolStub) };
    const { queryWithParameter } = proxyquire('./', {
      pg: pgStub,
    });
    const actual = await queryWithParameter('SELECT $1::text as message', ['Hello world!']);
    sinon.assert.calledWithExactly(pgStub.Pool, {
      connectionString: 'whatever',
      ssl: {
        rejectUnauthorized: false,
      },
    });
    sinon.assert.calledOnce(poolStub.connect);
    sinon.assert.calledWithExactly(clientStub.query, 'SELECT $1::text as message', ['Hello world!']);
    sinon.assert.match(actual, [{ message: 'Hello world!' }]);
    sinon.assert.calledWithExactly(clientStub.release, true);
  });
});

test result:

  69222273
    ✓ should query result (1350ms)


  1 passing (1s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   84.62 |       50 |     100 |   91.67 |                   
 index.js |   84.62 |       50 |     100 |   91.67 | 22                
----------|---------|----------|---------|---------|-------------------
  • Related