使用 sinon js 的假池连接

fake pool connection using sinon js

我只想伪造池连接和 在我所有的单元测试中使用连接。

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

我应该使用 sinon.js 来伪造池连接,这样我就无法访问实际的数据库,但未能成功实施。

我会告诉你如何测试“应该是正确的查询结果”的测试用例。

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 ::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 ::text as message', ['Hello world!']);
    sinon.assert.match(actual, [{ message: 'Hello world!' }]);
    sinon.assert.calledWithExactly(clientStub.release, true);
  });
});

测试结果:

  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                
----------|---------|----------|---------|---------|-------------------