简体   繁体   中英

Stubbing query() method of pg.Pool.prototype using sinon

I'm attempting to stub the query method of a connected pg.Pool object, to test the result of a generic GET backend method.

My db config file looks something like:

const {Pool} = require('pg');
require('dotenv').config();

const config = {
    host: process.env.HOST,
    user: process.env.USER,
    password: process.env.PASSWORD,
    database: process.env.DB_NAME,
    port: process.env.PORT,
    ssl: process.env.SSL_MODE,
}

module.exports = new Pool(config);

And my backend method:

const db = require('dbConfig.js');

exports.getData = async function () {
    var conn = await db.connect();
    var response = await conn.query(`SELECT * FROM data;`);
    conn.release();
    return response.rows;
}

I'm trying to use sinon to stub the result of the conn.query() call to return some test data, but the result in the test file is actual data from the database.

My test file is this:

const sinon = require('sinon');
const backendFile = require('backendFile');
const pg = require ('pg');

describe("Test", function () {
    let sampleData = [{
        a: '1',
        b: '2',
        c: '3',
    }]

beforeEarch(() => {
    const pgStub = sinon.stub(pg.Pool.prototype, 'query');
    pgStub.returns(sampleData)
});

it("test 1", async function () {
    let data = await backendFile.getData();
    console.log(data); // This line logs actual db data, not the sampleData var :(
    })
})

pool.connect returns an instance of pg.Client , so you are calling the query() function on pg.Client , not pg.Pool .

To stub the query() function on pg.Client would look like:

const pgStub = sinon.stub(pg.Client.prototype, 'query');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM